Dheeraj Joshi
Dheeraj Joshi

Reputation: 3147

Parsing empty Json array using gson

I am using gson to parse a JSON reply. The code works fine for proper JSON response. However if the JSON reply is empty array, The my code keeps complaining "Was expecting begin_object but got 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.

Could any one tell me any such methods exist in GSON API. Or how we can over come this issue?

EDIT: I have modified the response i get from the server.

Upvotes: 0

Views: 2149

Answers (1)

Ryan Stewart
Ryan Stewart

Reputation: 128879

You're already using the appropriate method. It's the JsonReader.hasNext() method as described in the JsonReader class docs:

Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().

You just need to switch from a do/while to a while loop. 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.

Upvotes: 1

Related Questions