Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
471 views
Welcome To Ask or Share your Answers For Others

1 Answer

I just changed ObjectB[] to List<ObjectB> into ObjectA declaration.

ArrayList<ObjectA> la = new ArrayList<ObjectA>();
List<ObjectA> list = new Gson().fromJson(json, la.getClass());

for (Object a : list)
{
   System.out.println(a);
}

and this is my result:

{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}]}

I think that in full generics era, if you do not have particular needs, you can switch from arrays to lists, you have many benefits that Gson also can use to do a flexible parsing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...