How to fix "expected begin_array but was begin_object" in Retrofit ?

begin_array means the json response is an array which will look something like this[{},{},..]begin_object means the json response is an object which will look something like this {....}

gson is one cool library that will provide us with cool tips in the form of errors while handling json responses. One such tip is "expected begin_array but was begin_object". These tips/errors are quite self explanatory, we can now look deeper into these errors.

While handling responses using retrofit, we often tend to come across an error "expected begin_array but was begin_object", which is thrown by gson. Obviously this means that we are trying to parse the response as if it is a json array response but when actually it is a json object response. But still we come across these errors a lot of time. We will be looking in detail about such situations in this post.

2. Parsing using POJO class

FYI : after pasting the response structure in http://www.jsonschema2pojo.org/ , set the source type to JSON and Annotation style to Gson , now click preview button and you can see generated pojo class/classes

In the above pojo classes, we have used @SerializedName annotation which will help us to map the class variables to respective keys in the response json. For example, in UserArray.java, the string variable userAddress is correctly mapped to user_address by using the @SerializedName annotation like this

@SerializedName("user_address")@Exposeprivate String userAddress;

The Example.javais for parsing the outer json object whereas UserArray.java is for parsing the inner json object which should be parsed as a list(since there is a list of objects in user_array)

The error "expected begin_array but was begin_object" occurs if you are trying to parse the above response using Call<List<Example>> call=request.getJson(); because by using<List<Example>> we are clearly making an array request but we need to make an object request since response is of the form {..}

Similarly we get the error"expected begin_object but was begin_array" when we are trying to make an object request were the response is of the form [{},{},..], which is a json array example. In such case we should make the call like Call<List<Example>>