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 com.google.gson.JsonSyntaxException: 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.

Output

Solution:

As we can see from the output, the code throws com.google.gson.JsonSyntaxException: 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.

Output

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

Output

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

About the author

Leave a Reply

Your email address will not be published.