0

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.

5
  • hope it helps : stackoverflow.com/questions/12380927/… Commented Apr 12, 2013 at 7:13
  • Are you sure the JSON response is {[]}? Because that's not valid JSON... something like this: {"list":[]} sounds better... if it's the latter I can help you... Commented Apr 13, 2013 at 0:20
  • Yes. JSON provider has modified the Response from server. I have edited the Original post Commented Apr 15, 2013 at 4:47
  • The "JSON response" is still missing a closing brace. Please verify that you've copied it correctly. Commented Apr 15, 2013 at 4:50
  • It was just copy paste error :D I have corrected it Commented Apr 15, 2013 at 6:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.