Reputation: 10777
I have seen similar questions about parsing json with dynamic keys, but could not figure out how to parse the following json:
{
"unknown":
{
"id":3980715,
"name":"namename",
"profileIconId":28,
"revisionDate":1451936993000
}
}
Here, the "unknown" key is dynamic, it can be anything. We do not know what it is.
I tried the following class:
public class MyResponseClass {
private Map<String, Object> myResponse;
//Getter and setter
}
But myResponse becomes null after using gson like the following:
return gson.fromJson(response, MyResponseClass.class);
So, how can i do this?
Thanks.
Upvotes: 0
Views: 87
Reputation:
Add an annotation to the field myResponse
.
public class MyResponseClass {
@SerializedName("unknown")
private Map<String, Object> myResponse;
//Getter and setter
}
Upvotes: 1
Reputation: 10777
I could manage to parse it like the following:
Type mapType = new TypeToken<Map<String, MyResponseClass>>() {}.getType();
Map<String, MyResponseClass> map = gson.fromJson(response, mapType);
and then iterated over map to get what I want.
Upvotes: 1
Reputation: 3071
Try this:
// String jsonStr = ...;
Gson gson = new Gson();
Map<String, Object> jsonData = new HashMap<String, Object>();
jsonData = (Map<String, Object>)gson.fromJson(jsonStr, Object.class);
Your JSON data will be stored in Map<String, Object>
(which is the simpliest way to store JSON data in Java).
So in this map at unknown
key you will have another map with id
, name
etc.
Upvotes: 0