Reputation: 375
I making an parser for json with gson and it based on object model method. My problem is that I have an object on the json where there are some other JsonObjects in it but I don't know there names so I can't use the SerializedName. Also the number of the JsonObjects on the initial object is random. How to iterate the objects from the initial object?
Json style:
"initial_obj": {
"random_name1": { }
"random_name50": { }
"random_name9": { }
}
Upvotes: 0
Views: 1278
Reputation: 46841
If the name of fields are not known in advance then convert it into Map<String, Object>
using TypeToken
String str = "{\"initial_obj\": {\"random_name1\": { },\"random_name50\": { },\"random_name9\": { }}}";
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(str, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
output:
{
"initial_obj": {
"random_name1": {},
"random_name50": {},
"random_name9": {}
}
}
Upvotes: 4