I have no control over this json, it comes from the third pary api.
If you do not have control over the data, the best solution is to create a custom deserializer, in my opinion:
class MyObjectDeserializer implements JsonDeserializer<MyObject> {
@Override
public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jObj = json.getAsJsonObject();
JsonElement jElement = jObj.get("tags");
List<String> tags = Collections.emptyList();
if(jElement.isJsonArray()) {
tags = context.deserialize(jElement.getAsJsonArray(), new TypeToken<List<String>>(){}.getType());
}
return new MyObject(jObj.getAsJsonPrimitive("name").getAsString(), tags);
}
}
What does he do to check whether "tags" JsonArrayor not. If so, he will deserialize it, as usual, otherwise you will not touch it and just create your object with an empty list.
, JSON:
Gson gson = new GsonBuilder().registerTypeAdapter(MyObject.class, new MyObjectDeserializer()).create();
List<MyObject> myObjects = gson.fromJson(json, new TypeToken<List<MyObject>>(){}.getType());
, :
MyObject{name='item 1', tags=[tag1]}
MyObject{name='item 2', tags=[tag1, tag2]}
MyObject{name='item 3', tags=[]}
MyObject{name='item 4', tags=[]}