0

I have a json like this



{

  "data": {

    "category": {

      "name_en": "Trend",

      "style": "normal"

    },

    "items": [

      {

        "title_en": "The Garfield Movie",

        "imdb_rank": 5.8,

        "country": "US",

        "company": " Columbia Pictures"

      }

    ]

  },

  "type": "category"

}

And I want to get data value and then using items. This is my code

map = new Gson().fromJson(
    new Gson().toJson((HashMap<String, Object>) map.get("data")),
    new TypeToken<HashMap<String, Object>>() {}.getType()
);

But I got this error: 07-09 19:50:16.615 12794 12794 E AndroidRuntime: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.HashMap

I'm beginner at this can anybody tell me how to do it with Gson ?

Get HashMap value into HashMap

1

1 Answer 1

4

You encounter this issue because the Gson library uses its own map implementation which is LinkedTreeMap and it is not a subclass of HashMap, as the error indicates about this. There are some solutions to this, you can adjust the code and avoid the explicit cast to HashMap when dealing with deserialization. Instead, you can allow Gson to directly deserialize the JSON into the appropriate Map type that it supports.

below is an example of code:

public class Example {
    public static void main(String[] args) {
        String json = "{Your JSON}";

        Gson gson = new Gson();
        Map<String, Object> outerMap = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
        Map<String, Object> dataMap = gson.fromJson(gson.toJson(outerMap.get("data")), new TypeToken<Map<String, Object>>() {}.getType());

        System.out.println(dataMap);
    }
}

this should help to solve the issue. Key moments to remember and note:

  1. Gson by default uses LinkedTreeMap for JSON objects, not HashMap. a. for this I've used Map<String, Object> directly without casting it to HashMap.
  2. The fromJson method directly handles the conversion, and the proper type is inferred using TypeToken.

I'm not an experienced one as well, but hope this helps.

Not the answer you're looking for? Browse other questions tagged or ask your own question.