Android: Parse Json Response When A Key Can Be A Json Object Or A Json Array
I am fetching data from API provided by our Backend team. One of the keys data sometimes contains JSONObject and sometimes it contains JSONArray. I am using GSON to parse the respo
Solution 1:
You need to use a custom JsonDeserializer. Here's the solution :
publicclassCollectionListItem {
@SerializedName ("type")
String type;
@SerializedName ("order")
Integer order;
@SerializedName ("id")
Integer id;
@SerializedName ("type_id")
Integer typeId;
DataType1 dataType1;
List<DataType2> dataType2;
List<DataType3> dataType3;
finalstaticStringDATA_TYPE_1="SHOP";
finalstaticStringDATA_TYPE_2="TOP_AUDIOS";
finalstaticStringDATA_TYPE_3="MEDIA_COLLECTION";
//Public getters and setterspublicstaticclassCollectionItemDeserializerimplementsJsonDeserializer<CollectionListItem> {
@Overridepublic CollectionListItem deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)throws JsonParseException {
CollectionListItemcollectionItem=newGson().fromJson(json, CollectionListItem.class);
JsonObjectjsonObject= json.getAsJsonObject();
if (collectionItem.getType() != null) {
JsonElementelement= jsonObject.get("data");
switch(collectionItem.getType()){
case CollectionListItem.DATA_TYPE_1 :
collectionItem.dataType1 = newGson().fromJson(element, DataType1.class);
break;
case CollectionListItem.DATA_TYPE_2:
List<DataType2> values = newGson().fromJson(element, newTypeToken<ArrayList<DataType2>>() {}.getType());
collectionItem.dataType2 = values;
break;
case CollectionListItem.DATA_TYPE_3:
List<DataType3> values_ = newGson().fromJson(element, newTypeToken<ArrayList<DataType3>>() {}.getType());
collectionItem.dataType3 = values_;
break;
}
}
return collectionItem;
}
}
}
DataType1, DataType2, etc are the individual classes for different responses.
Also, add this line to register your custom deserializer with gson
Gson gson = newGsonBuilder()
.registerTypeAdapter(CollectionListItem.class,
new CollectionListItem.CollectionItemDeserializer())
.create();
Post a Comment for "Android: Parse Json Response When A Key Can Be A Json Object Or A Json Array"