역직렬화하는 동안 Gson은 JSON 개체를 기대할 수 있지만 JSON 배열을 찾을 수 있습니다. 하나에서 다른 것으로 변환할 수 없기 때문에 "JsonSyntaxException:java.lang.IllegalStateException:BEGIN_OBJECT가 예상되지만 BEGIN_ARRAY와 같은 오류가 발생할 수 있습니다. " 런타임에.
예시
import com.google.gson.Gson; public class GsonErrorTest { public static void main(String args[]) throws Exception { String json = "{\"employee\":[{\"name\":\"Raja Ramesh\", \"technology\":\"java\"}]}"; Gson gson = new Gson(); Software software = gson.fromJson(json, Software.class); System.out.println(software); } } class Software { Employee employee; } class Employee { String name; String technology; }
출력
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)at com.google.gson.Gson.fromJson(Gson.java:795) at com.google.gson.Gson.fromJson(Gson.java:761) at com.google.gson.Gson.fromJson(Gson.java:710) at com.google.gson.Gson.fromJson(Gson.java:682) at BeginObjectError.main(BeginObjectError.java:7) Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14 at com.google.gson.stream.JsonReader.expect(JsonReader.java:339) at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
POJO 유형을 컬렉션 또는 배열 유형으로. 아래 예에서는 목록 을 사용할 수 있습니다. POJO 클래스의 컬렉션입니다.
예시
import java.util.List; import com.google.gson.Gson; public class GsonListTest { public static void main(String args[]) throws Exception { 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; @Override public String toString() { return "Software [employees=" + employees + "]"; } } class Employee { String name; String technology; @Override public String toString() { return "Employee [name=" + name + ", technology=" + technology + "]"; } }
출력
Software [employees=[Employee [name=Raja Ramesh, technology=Java]]]