Is there a simple way to deserialize a value that may be either a String or a List<String>?
I have to process a large JSON that I'll abbreviate like:
{"A": {"item1": 1,
...
"itemN": "SomeString",
...
"itemM": 123.45},
"B": { ... },
"C": { ... },
}
And sometimes it looks like this:
{"A": {"item1": 1,
...
"itemN": ["SomeString1", "SomeString2"],
...
"itemM": 123.45},
"B": { ... },
"C": { ... },
}
I deserialize with:
MyData data = new Gson().fromJson(rxJSON, DataClass.class);
Where DataClass:
@Parcel
public class DataClass {
@SerializedName("A")
private AClass groupA;
@SerializedName("B")
private BClass groupB;
@SerializedName("C")
private BClass groupC;
... getters/setters ...
}
and AClass:
@Parcel
public class AClass {
@SerializedName("item1")
private int item1;
...
@SerializedName("itemN")
private List<String> itemN;
...
@SerializedName("itemM")
private float itemM;
... getters/setters ...
}
Ideally, I'd like to use AClass for both JSONs, and in the case where itemN is a String, simply treat it as if it were a single element List<String> (ie. treat "SomeString" as ["SomeString"]). After deserializing, I always want to access it as a list for simplicity in the rest of my code.
I've seen suggestions for Polymophism solutions and solutions suggesting attempting to deserialize with one version of a class assuming one type (such as String) and in an exception catch deserialize with a version of the class assuming the other type (such as List<String>). Other solutions suggest a more manual/piece-wise deserialization where it would deserialize only one level of the JSON hierarchy at a time until I came to itemN and then check it's type. It seems like there should be a simpler way. Is there?