I have a JSON that is either a single object or an array of the same object. Is there a way to parse this data using Gson where it'll distinguish between the single object vs the array?
The only solution I currently have for this is to manually parse the json and surround that with a try catch. First I'll try parsing it as a single object, if it fails, it'll throw an exception and then I'll try to parse it as an array.
I don't want to parse it manually though...that would take me forever.
Here's an idea of what's happening.
public class ObjectA implements Serializable{
public String variable;
public ObjectB[] objectb; //or ObjectB objectb;
public ObjectA (){}
}
Here's the object that can either be an array or a single object.
public class ObjectB implements Serializable{
public String variable1;
public String variable2;
public ObjectB (){}
}
And then when interacting with the json response. I'm doing this.
Gson gson = new Gson();
ObjectA[] objectList = gson.fromJson(response, ObjectA[].class);
When the array of ObjectA's are being serialized, the json contains either an array or single object for ObjectB.
[
{
"variable": "blah blah",
"objectb": {
"variable1": "1",
"variable2": "2"
}
},
{
"variable": "blah blah",
"objectb": {
"variable1": "1",
"variable2": "2"
}
},
{
"variable": "blah blah",
"objectb": [
{
"variable1": "1",
"variable2": "2"
},
{
"variable1": "1",
"variable2": "2"
}
]
}
]
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…