Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

java - Using GSON to parse json object vs json array

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...