I need to deserialize this json:
{
"17": {
"entity_id": "17",
"attribute_set_id": "4",
"type_id": "virtual",
},
"18": {
"entity_id": "18",
"attribute_set_id": "9",
"type_id": "virtual"
}
}
but using retrofit and Gson it seems to be impossible.
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://endpoint/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
So, how can I deserialize this creature? What type can I use?
This is Map where "17"
is a key and
{ "entity_id": "17", "attribute_set_id": "4", "type_id": "virtual", }
is a object.
Try HashMap.
You could create a Java class (say Item
) to include member variables ( entity_id
, attribute_set_id
and type_id
) - I created this Gist , and use JSONObject
to do something like this:
JSONObject yourJSON = new JSONObject(jsonString);
//This will iterate through 17, 18, etc
Iterator<String> keysIterator = yourJSON .keys();
while(keysIterator.hasNext()) {
String key = keysIterator.next();
JSONObject actualObj = (JSONObject)yourJSON.get(key);
//Here, supposing you had defined Item class, using Gson, you'd do this:
Item thisItem = (new Gson()).fromJson(actualObj.toString(), Item.class);
//From here you can call thisItem.getEntityId(), etc
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.