I am having trouble deserializing a java object because the field ("information") inside the object can be one of two possible types: either ArrayList or just String.Here - this is what I have done so far:
First create the Base class:
public class Base {
}
Next, create subclasses:
public class GoodInfo extends Base {
public ArrayList<MyCustomObject> info;
}
public class BadInfo extends Base {
public String info;
}
So, now I would like to parse my JSON, which is an ArrayList of underlying objects (i.e. an ArrayList of objects, where each object is either an ArrayList or String):
Type listOfBase = new TypeToken<ArrayList<Base>>(){}.getType();
ArrayList<Base> resp=gson.fromJson(jsonText, listOfBase);
I know that for this I have to write my own deserializer. Deserializer is as follows:
private class MyCustomDeserializer implements JsonDeserializer<DateTime> {
public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
}
}
, , , , . - , ?
, :
private class MyCustomDeserializer implements JsonDeserializer<DateTime> {
public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
GoodInfo goodInfo=SOMEHOW TRY TO DESERIALIZE json INTO A GoodInfo object
return goodInfo;
} catch {
}
try {
BadInfo badInfo=SOMEHOW TRY TO DESERIALIZE json INTO A BadInfo object
return badInfo;
} catch {
throw new JsonParseException("Could not deserialize");
}
}
}
context.deserialize json, GSON:
. , JsonDeserializer.deserialize(JsonElement, Type, JsonDeserializationContext). , Gson .
, ?