Skip to content

Gson – Fix: Expected BEGIN_OBJECT but was BEGIN_ARRAY

Gson – Fix Expected BEGIN_OBJECT but was BEGIN_ARRAY example shows how to fix java.lang.IllegalStateException exception while parsing JSON using the Gson library in Java.

What causes this exception?

This exception occurs when the JSON data contains a JSON array but we try to parse it as a JSON object. Consider the below given JSON.

And here is the Java code to parse/read it using Gson.



As we can see from the output, the code throws java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY exception.

The reason is, our JSON contains an array of Student objects, not an individual object. But the code tries to parse it as an object. In short, when we try to parse a JSON array as an object instead of an array, Gson throws this exception.

The correct way is to parse the JSON array into a Java array is as given below.


We can also parse JSON array to a Java list as given below.


Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.