简体   繁体   English

使用gson解析空的Json数组

[英]Parsing empty Json array using gson

I am using gson to parse a JSON reply. 我正在使用gson解析JSON答复。 The code works fine for proper JSON response. 该代码可以正常进行JSON响应。 However if the JSON reply is empty array, The my code keeps complaining "Was expecting begin_object but got end_array" 但是,如果JSON回复为空数组,则我的代码会一直抱怨“原本是begin_object但得到了end_array”

JSON response
    {
        "list" : {
                  "data" : [

                  ]
         }
    }

My code 我的密码

try {
    jsonReader.beginArray();
        do{
        jsonReader.beginObject();
            while(jsonReader.hasNext()){
                      // Parse all data
              jsonReader.endObject();
            } while(jsonReader.hasNext());
            jsonReader.endArray();
} catch (IOException e) {
//Exception
}

I know what the above exception mean, It simply means it was expecting object inside an array to process. 我知道上面的异常是什么意思,它只是意味着它期望数组中的对象进行处理。 But since it is an empty array it gives exception. 但是由于它是一个空数组,所以会给出异常。

But i have looked at the api guide, and there are no methods to check whether the JSON is an empty array or the next object in input stream is object or end of array etc. 但是我看过api指南,没有方法可以检查JSON是空数组还是输入流中的下一个对象是对象还是数组末尾等。

Could any one tell me any such methods exist in GSON API. 任何人都可以告诉我GSON API中是否存在这样的方法。 Or how we can over come this issue? 还是我们能克服这个问题?

EDIT: I have modified the response i get from the server. 编辑:我已经修改了我从服务器得到的响应。

You're already using the appropriate method. 您已经在使用适当的方法。 It's the JsonReader.hasNext() method as described in the JsonReader class docs : 这是JsonReader类docs中描述的JsonReader.hasNext()方法:

Within array handling methods, first call beginArray() to consume the array's opening bracket. 在数组处理方法中,首先调用beginArray()以消耗数组的左括号。 Then create a while loop that accumulates values, terminating when hasNext() is false. 然后创建一个while循环来累积值,并在hasNext()为false时终止。 Finally, read the array's closing bracket by calling endArray(). 最后,通过调用endArray()阅读数组的右括号。

You just need to switch from a do/while to a while loop. 您只需要从do / while循环切换到while循环即可。 Your current code requires there to always be at least one object in the array because a do/while doesn't check the condition until the end of the loop. 您当前的代码要求数组中至少有一个对象,因为do / while直到循环结束才检查条件。

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

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