GSON throwing Expected BEGIN_OBJECT but was BEGIN_ARRAY?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
This Gson error means your Java type does not match the JSON structure being parsed. Gson expected a single JSON object, but the input actually starts with a JSON array, so the fix is to change either the JSON or the target Java type.
What the Error Really Means
If the JSON begins with a left square bracket, then the payload is an array:
If your code tries to parse that into one object:
Gson complains because User.class describes one object, not a list of objects.
That is exactly what "Expected BEGIN_OBJECT but was BEGIN_ARRAY" means.
Fix 1: Parse into a List
If the payload is truly an array, parse it into a collection.
This is the most common fix because APIs often return lists even when the developer expects a single record.
Fix 2: Parse a Single Object When the JSON Is an Object
If the JSON really should be one object, then the payload itself must look like this:
Then the original object parse is correct:
So the first debugging question is simple:
- is the payload an object
- or is it an array
Do not guess. Print the raw JSON and inspect the first non-whitespace character.
Watch for Wrapper Objects
Another common case is that the server returns an object containing an array:
In that case, the correct Java type is neither User nor List<User> directly. It is a wrapper class:
This is why reading the payload shape matters more than memorizing one fix.
Debug the Actual Payload, Not the API Docs Alone
Sometimes the docs say "returns a user", but the real endpoint returns a one-element array. Or the endpoint changes after a backend update. The safest way to debug is to log the raw response body before Gson touches it.
Once you know whether the JSON starts with:
- '
[for an array' - '
{"for an object'
the type mismatch usually becomes obvious.
Common Pitfalls
- Parsing an array response into a single object class.
- Forgetting to use
TypeTokenwhen deserializing generic collections such asList<User>. - Assuming the payload is flat when the real response has a wrapper object around the array.
- Trusting an API description instead of inspecting the actual JSON returned at runtime.
- Trying to "fix" Gson configuration when the real issue is just a mismatched target type.
Summary
- The error means the JSON begins with an array, but your code asked Gson for an object.
- If the payload is an array, deserialize into a collection such as
List<User>. - If the payload is a wrapper object, create a wrapper class that matches it.
- Log and inspect the raw JSON before changing parsing code.
- Gson usually is not the problem here; the Java type and JSON shape simply do not match.

