Home > Mobile >  Convert JSON to MAP using GSON library
Convert JSON to MAP using GSON library

Time:10-21

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:

[{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}

CodePudding user response:

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

  • Related