0

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.

yrazlik
  • 10,411
  • 33
  • 99
  • 165

3 Answers3

1

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.

yrazlik
  • 10,411
  • 33
  • 99
  • 165
1

Add an annotation to the field myResponse.

public class MyResponseClass {
    @SerializedName("unknown")
    private Map<String, Object> myResponse;

    //Getter and setter
}
0

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.

coolguy
  • 3,011
  • 2
  • 18
  • 35