Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert JSON to MAP using GSON library

I want to convert JSON response to Map what is the best approach to get the desired output using GSON library.

I try this and I’m getting only the ArrayList value.

Map<String, Object> map = gson.fromJson(response, HashMap.class);
ArrayList responseOptions = (ArrayList) map.get("data");

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{language=Java, value=8}, {language=Ruby, value=7}, {language=Python, value=7}]

Sample JSON Response

{
    "data":[
    {
    "language":"Java","value":"8"
    },
    {
    "language":"Ruby","value":"7"
    },
    {
    "language":"Python","value":"6"
    }]
}

Desired Output in Map
{Java=8, Ruby=7, Python=6}

>Solution :

Test code

    String str = "{\n" +
            "    \"data\":[\n" +
            "    {\n" +
            "    \"language\":\"Java\",\"value\":\"8\"\n" +
            "    },\n" +
            "    {\n" +
            "    \"language\":\"Ruby\",\"value\":\"7\"\n" +
            "    },\n" +
            "    {\n" +
            "    \"language\":\"Python\",\"value\":\"6\"\n" +
            "    }]\n" +
            "}";
    Map map = new Gson().fromJson(str, Map.class);
    List data = (List) map.get("data");
    Map<String, String> result = new HashMap<>();
    for (Object o : data) {
        Map m = (Map) o;
        result.put(m.get("language").toString(), m.get("value").toString());
    }
    System.out.println(result);

Test result

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading