I want to parse a json object containing dynamic field type using Gson:
{
"rows":
[
{
"id": "1",
"interventions": [
{
"type": "type1",
"label": "label 1"
},
{
"type": "type2",
"label": ["label 1","label 2"]
},
{
"type": "type3",
"label": "label 3",
}
]
}
]
}
As you can see that the "label" field can be String or list of strings.
I wrote a customized deserializer to handle this issue, it works if the "interventions" field has only one element (regardless the "label" field is a string or list):
{"rows":
[
{
"id": "1",
"interventions": [
{
"type": "type1",
"label": "label 1"
}
]
}
]
}
But always throws com.google.gson.JsonArray cannot be cast to com.google.gson.JsonPrimitive exception if there are more than one "interventions" element.
Here is the customized deserializer:
public class CustomDeserializer implements JsonDeserializer<InterventionsModel> {
@Override
public InterventionsModel deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
if(je != null && je.getAsJsonObject()!=null) {
JsonPrimitive jp = je.getAsJsonObject().getAsJsonPrimitive("label");
if (jp != null && jp.isString()) {
String label = jp.getAsString();
List<String> list = new ArrayList<String>(1);
list.add(label);
InterventionsModel interventionsModel = new InterventionsModel();
interventionsModel.setLabel(list);
return interventionsModel;
}
}
return new Gson().fromJson(je, InterventionsModel.class);
}
}
In the calling method:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(InterventionsModel.class, new CustomDeserializer());
builder.setPrettyPrinting();
Gson gson = builder.create();
The classes for the objects are:
public class ResultsModel {
private List<RowModel> rows;
//getter and setter ..
}
public class RowModel {
private String id;
private List<InterventionsModel> interventions;
//getter and setter
}
public class InterventionsModel {
private String type;
private List<String> label;
//setter and getter
}
Could someone please help?