Gson – Solution: Expected BEGIN_ARRAY but was BEGIN_OBJECT example shows how to fix com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT exception while using the Gson in Java.
What causes this exception?
This exception is thrown by the Gson library when we try to parse JSON Object as a JSON array. Consider the below given JSON.
1 2 3 4 5 |
{ "id": 1, "name": "Bob", "departments": ["HR", "ERP"] } |
The above JSON contains a JSON object representing an employee. Let’s see what happens when we try to parse it as an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.javacodeexamples.gsonexamples; import java.util.List; import com.google.gson.Gson; public class GsonBeginArrayException { public static void main(String[] args) { String jsonData = "{\"id\": 1,\"name\": \"Bob\",\"departments\": [\"HR\", \"ERP\"]}"; Employee[] employees = new Gson().fromJson(jsonData, Employee[].class); System.out.println(employees); } } class Employee{ private String id; private String name; List<String> departments; public List<String> getDepartments() { return departments; } public void setDepartments(List<String> departments) { this.departments = departments; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ at com.google.gson.Gson.fromJson(Gson.java:1238) at com.google.gson.Gson.fromJson(Gson.java:1137) at com.google.gson.Gson.fromJson(Gson.java:1047) at com.google.gson.Gson.fromJson(Gson.java:982) at com.javacodeexamples.gsonexamples.GsonBeginArrayException.main(GsonBeginArrayException.java:13) Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:358) at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:70) at com.google.gson.Gson.fromJson(Gson.java:1227) ... 4 more |
Solution:
This exception is thrown by the Gson when we try to parse JSON object as JSON array. Here is how to correctly parse JSON object.
1 2 3 4 5 |
String jsonData = "{\"id\": 1,\"name\": \"Bob\",\"departments\": [\"HR\", \"ERP\"]}"; Employee empObject = new Gson().fromJson(jsonData, Employee.class); System.out.println(empObject.getId() + ", " + empObject.getName() + ", " + empObject.getDepartments()); |
Output
1 |
1, Bob, [HR, ERP] |
Please let me know your views in the comments section below.