我正在尝试将json读入对象。
测试.json:
{
"errorCode": "503",
"errorMessage": "ERR_MESSAGE",
"entities": {
"key1": "value1",
"key2": "value2"
}
}
这是我想从json创建的ErrorDetail模型:
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ErrorDetail {
private String errorCode;
private String errorMessage;
private Map<String, List<String>> entities;
private String errorSource;
}
测试解析的公共main方法:
public static void main(String[] args) {
String json = new String(Files.readAllBytes(Paths.get("src/main/resources/test.json")));
Gson gson = new Gson();
ErrorDetail errorDetail = gson.fromJson(json, ErrorDetail.class);
System.out.println(errorDetail);
}
然而我得到了一个例外:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 5 column 14 path $.entities.
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:932)
at com.google.gson.Gson.fromJson(Gson.java:897)
at com.google.gson.Gson.fromJson(Gson.java:846)
at com.google.gson.Gson.fromJson(Gson.java:817)
at com.nordstrom.Main.main(Main.java:28)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 5 column 14 path $.entities.
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:351)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
... 5 more
我做错了什么?请协助,我已经调试和寻找解决方案一整天,没有结果。
1条答案
按热度按时间yuvru6vn1#
您的模型不正确。它应该是: