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
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:
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.I'm not an experienced one as well, but hope this helps.