简体   繁体   English

使用GSON解析json对象与json数组

[英]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. 我有一个JSON,它可以是单个对象,也可以是同一个对象的数组。 Is there a way to parse this data using Gson where it'll distinguish between the single object vs the array? 有没有办法使用Gson解析这些数据,它会区分单个对象和数组?

The only solution I currently have for this is to manually parse the json and surround that with a try catch. 我目前唯一的解决方案是手动解析json并使用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. 然后在与json响应交互时。 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. 当ObjectA的数组被序列化时,json包含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"
            }
        ]
    }
]

I just changed ObjectB[] to List<ObjectB> into ObjectA declaration. 我刚刚将ObjectB[]更改为List<ObjectB>ObjectA声明中。

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. 我认为在完整的泛型时代,如果你没有特殊的需求,你可以从数组切换到列表,你有很多好处,Gson也可以使用它来进行灵活的解析。

Try to use com.google.gson.JsonParser. 尝试使用com.google.gson.JsonParser。

        String jsonString = "object json representation";
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(jsonString);

        if (jsonElement.isJsonArray()) {
            // some logic
        }

There are different ways to get your object using the JsonElement instance, for example - simply using the com.google.gson.Gson methods : 有不同的方法可以使用JsonElement实例获取对象,例如 - 只需使用com.google.gson.Gson方法:

public <T>  T fromJson(com.google.gson.JsonElement json, java.lang.Class<T> classOfT) throws com.google.gson.JsonSyntaxException 

public <T>  T fromJson(com.google.gson.JsonElement json, java.lang.reflect.Type typeOfT) throws com.google.gson.JsonSyntaxException

So, study the JsonElement, JsonArray, JsonPrimitive, JsonNull and JsonObject classes. 因此,研究JsonElement,JsonArray,JsonPrimitive,JsonNull和JsonObject类。 Believe, they have an adequate interface to recover your object. 相信,他们有足够的界面来恢复你的对象。

Can you try/catch it by first trying to parse the array, then falling back to parsing the single object class? 你可以先尝试解析数组,然后再回到解析单个对象类来尝试/捕获它吗?

You could also do a real simple test and look to the first non whitespace character in the string you are deseralizing, if it is a "{" it is a single object, if it is a "[" it is an array 您还可以进行一个真正的简单测试,并查看要解除链接的字符串中的第一个非空格字符,如果它是“{”它是单个对象,如果它是“[”它是一个数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM