Parsing dynamically change element using GSON

// Data as a JSON array 
{
"success": true,
"data": [
]
}
// Data as a JSON object 
{
"success": true,
"data": {
}
}
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();

@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
}

--

--

--

Passionate about learning

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

HTML 5 Interview Questions and Answers 😃

Asset Protection Law

How we designed a plugin for Ubidots

Arbitrary Precision & Arithmetic

Effective Management of Remote & Distributed Software Engineers

Magical Performance Improvements with Redis Caching in Django

YouTube Video | HTML Crash Course — 2

Manually provisioning web stack on AWS:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
jigar mori

jigar mori

Passionate about learning

More from Medium

Kotlin vs Java Example: Part - 4 | Erselan Khan

Resolving HAXM Issue in Android Studio for Windows

What is the difference between implementation and api gradle configuration?

Handling project dependencies using type-safe project accessor