Gson阅读无法解析对象Map字段

xhv8bpkk  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(145)

我正在尝试将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

我做错了什么?请协助,我已经调试和寻找解决方案一整天,没有结果。

yuvru6vn

yuvru6vn1#

您的模型不正确。它应该是:

@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ErrorDetail {
    private String errorCode;
    private String errorMessage;
    // private Map<String, List<String>> entities;
    private Map<String, String> entities;
    private String errorSource;
}

相关问题