Making Gsonrequest To Accept Empty List Or Null Array
I have a Json data to be pulled from a server. This data contains several objects and arrays. The first model is as follows: { 'results': [ { 'id': '17', 'name':
Solution 1:
Actually your json response should return an empty array not a string for null cases. But if you don't have an option to change server's response then you may try to write a custom json deserializer:
classChildDeserializerimplementsJsonDeserializer<ChildHolder> {
@Overridepublic ChildHolder deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)throws JsonParseException {
StringcurrentValueOfChild= json.toString();
Log.d("ChildDeserializer", "ChildDeserializer: child=" + currentValueOfChild);
ChildHolderchildHolder=null;
if (json instanceof JsonArray) {
Log.d("ChildDeserializer", "ChildDeserializer: We have an array for 'child'");
TypelistType=newTypeToken<List<Child>>() {}.getType();
JsonArray jsonArray= json.getAsJsonArray();
childHolder = newChildHolder();
childHolder.childList = context.deserialize(jsonArray, listType);
}
return childHolder;
}
}
Your response java model should look like below:
classResponse{
List<Result> results;
}
classResult{
privateString id, name;
private ChildHolder child;
}
classChildHolder{
privateList<Child> childList;
}
classChild{
privateString id, name;
}
Apply deserializer while parsing json to java model:
String jsonTest1 ="{\"results\":[{\"id\":\"17\",\"name\":\"Accessories\",\"child\":[{\"id\":\"371\",\"name\":\"Belt\"},{\"id\":\"55\",\"name\":\"Derp\"}]}]}";
String jsonTest2 ="{\"results\":[{\"id\":\"19\",\"name\":\"Stuff\",\"child\":\"\"}]}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(ChildHolder.class, new ChildDeserializer());
Gson gson = gsonBuilder.create();
Response response1 = gson.fromJson(jsonTest1, Response.class);
Response response2 = gson.fromJson(jsonTest2, Response.class);
Also please read this link for further information.
Solution 2:
Another option for writing a custom serializer is to simply convert the empty string to an empty array in the JSON. Then your class can remain the way it is:
classChildDeserializerimplementsJsonDeserializer<CategoryModel>
{
@Override
public ChildHolder deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = json.getAsObject();
JsonElement e = obj.get("child");
if (e.isJsonPrimitive()) // it's a String
{
obj.remove("child");
obj.add("child", new JsonArray());
}
returnnew Gson().fromJson(obj, CategoryModel.class);
}
}
Post a Comment for "Making Gsonrequest To Accept Empty List Or Null Array"