Parsing dynamically change element using GSON

jigar mori
2 min readJan 9, 2021

--

As a mobile developer working with the API integration is a kind of daily task, We mostly use Retrofit for it with GSON. And for that kind of implementation we usually creating the POJO for our API response. But some time after all the implementation the type of element could change according some conditions.

// Data as a JSON array 
{
"success": true,
"data": [
]
}

As we can see data is coming as a JSON array in regular case but when there is no data available in array server was sending the object instead of array. This kind of dynamic data type change could be happen some time.

// Data as a JSON object 
{
"success": true,
"data": {
}
}

The simple solution for that would be we change it from backend, But sometime it could be third party response and you didn't have have control over it.

To resolve this first solution would be to use JsonDeserializer and then put this deserializer class as Typeadapter to gson

private static class MyPojoClassTypeAdapter implements JsonDeserializer<List<MyPojoClass>> {
public List<MyPojoClass> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<MyPojoClass> vals = new ArrayList<MyPojoClass>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
vals.add((MyPojoClass) ctx.deserialize(e, MyPojoClass.class));
}
} else if (json.isJsonObject()) {
vals.add((MyPojoClass) ctx.deserialize(json, MyPojoClass.class));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return vals;
}
}
Type myPojoClassListType = new TypeToken<List<MyPojoClass>>() {}.getType();

Gson gson = new GsonBuilder()
.registerTypeAdapter(myPojoClassListType, new MyPojoClassTypeAdapter())
.create();

Another way is to use data as jsonelement in our pojo and then use getter to return as desire object


@Expose
@SerializedName("data")
var dataElement: JsonElement? = null,
var dataItem: MutableList<MyPojoClass>? = mutableListOf()
get() {
var returnList = mutableListOf<MyPojoClass>()
if (dataElement!= null) {
if (dataElement is JsonArray) {
returnList = YourDataComponentForArray(dataElement)!!.toMutableList()
}
}
return returnList
}
//Utility fun to convert data into array or objectfun YourDataComponentForObject(data: JsonElement?): MyPojoClass? {
val type = object : TypeToken<MyPojoClass?>() {}.type
val item: MyPojoClass= Gson().fromJson(data, type)
return item
}

fun YourDataComponentForArray(data: JsonElement?): List<MyPojoClass>? {
val type = object : TypeToken<List<MyPojoClass?>?>() {}.type
val items: List<MyPojoClass> = Gson().fromJson<List<MyPojoClass>>(data, type)
return items
}

It is just simple example of handling dynamic data in parsing but we can modified it for any kind of dynamic use.

Hope you enjoy!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

jigar mori
jigar mori

No responses yet

Write a response