How can I convert JSON to a HashMap using Gson?

前端 未结 16 2577
臣服心动
臣服心动 2020-11-22 05:14

I\'m requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn\'t hard at all but the other way seems to

16条回答
  •  一个人的身影
    2020-11-22 05:48

    I had the exact same question and ended up here. I had a different approach that seems much simpler (maybe newer versions of gson?).

        Gson gson = new Gson();
        Map jsonObject = (Map) gson.fromJson(data, Object.class);
    

    with the following json

    {
      "map-00": {
        "array-00": [
          "entry-00",
          "entry-01"
         ],
         "value": "entry-02"
       }
    }
    

    The following

        Map map00 = (Map) jsonObject.get("map-00");
        List array00 = (List) map00.get("array-00");
        String value = (String) map00.get("value");
        for (int i = 0; i < array00.size(); i++) {
            System.out.println("map-00.array-00[" + i + "]= " + array00.get(i));
        }
        System.out.println("map-00.value = " + value);
    

    outputs

    map-00.array-00[0]= entry-00
    map-00.array-00[1]= entry-01
    map-00.value = entry-02
    

    You could dynamically check using instanceof when navigating your jsonObject. Something like

    Map json = gson.fromJson(data, Object.class);
    if(json.get("field") instanceof Map) {
      Map field = (Map)json.get("field");
    } else if (json.get("field") instanceof List) {
      List field = (List)json.get("field");
    } ...
    

    It works for me, so it must work for you ;-)

提交回复
热议问题