Lỗi JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY xảy ra khi JSON là array nhưng POJO expect object (hoặc ngược lại).
Ví dụ gây lỗi
String json = "{\"employee\":[{\"name\":\"Raja Ramesh\",\"technology\":\"java\"}]}";
// JSON: "employee" là ARRAY [{}]
// POJO: Software { Employee employee; } -> expect OBJECT {}
Gson gson = new Gson();
Software sw = gson.fromJson(json, Software.class); // ERROR!
class Software { Employee employee; }
class Employee { String name; String technology; }
Error Stack Trace
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14
Giải pháp: Sửa POJO dùng Collection/Array
import java.util.List;
import com.google.gson.Gson;
public class GsonListFixTest {
public static void main(String[] args) {
String jsonString = "{\"employees\":[{\"name\":\"Raja Ramesh\",\"technology\":\"Java\"}]}";
Gson gson = new Gson();
Software software = gson.fromJson(jsonString, Software.class);
System.out.println(software);
}
}
class Software {
List<Employee> employees; // DÙNG LIST THAY VÌ SINGLE OBJECT
@Override public String toString() { return "Software[employees=" + employees + "]"; }
}
class Employee {
String name; String technology;
@Override public String toString() { return "Employee[name=" + name + ", tech=" + technology + "]"; }
}
Output
Software[employees=[Employee[name=Raja Ramesh, tech=Java]]]
Các trường hợp thường gặp & Fix
| JSON Structure | POJO Sai | POJO Đúng |
|---|---|---|
{"items":[...]} |
Item items; |
List<Item> items; hoặc Item[] items; |
[...] (root array) |
MyObject obj; |
List<MyObject> list; hoặc MyObject[] arr; |
{"data":{...}} |
List<Data> data; |
Data data; |
Debug Tip
- In raw JSON string ra console trước khi parse.
- Dùng
JsonParser.parseString(json)kiểm tra structure (JsonObject vs JsonArray). - Online tool: jsonlint.com, jsonformatter.org validate structure.
Lưu ý
Gson 2.10+ có JsonAdapter và TypeAdapter cho custom deserialization phức tạp hơn, nhưng fix POJO type đúng là giải pháp chuẩn.