【问题标题】:Java Spring JSON parse error: JSON with arrays parsing error for java. Why?Java Spring JSON 解析错误:Java 的带有数组的 JSON 解析错误。为什么?
【发布时间】:2020-10-30 23:52:01
【问题描述】:
org.springframework.web.client.RestClientException: Error while extracting response for type [class com.radar.dto.WorldDTO] and content type [application/json;charset=UTF-8]; 
nested exception is org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Cannot deserialize instance of `com.radar.dto.WorldDTO` out of START_ARRAY token; 
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.radar.dto.WorldDTO` out of START_ARRAY token
 at [Source: (PushbackInputStream); line: 1, column: 1]

我正在尝试获取的 JSON 格式:

[
    {
        "id": "110",
        "name": "England",
        "areas": [
            {
                "id": "1620",
                "name": "London"
            },
            ...
        ]
    },
    ...
]

dto 类:

@Data
public class WorldDTO {
    private List<CountryDTO> countries;
}

@Data
private static class CountryDTO {
    @JsonProperty(value = "id")
    private String id;

    @JsonProperty(value = "name")
    private String name;

    @JsonProperty(value = "areas")
    private List<AreaDTO> areas;
}

@Data
public class AreaDTO {
    @JsonProperty(value = "id")
    private String id;

    @JsonProperty(value = "name")
    private String name;
}

我调用 API 的一段代码:

RequestEntity<?> request = new RequestEntity<>(HttpMethod.GET, uri);
ResponseEntity<WorldDTO> response = restTemplate.exchange(request, new ParameterizedTypeReference<>() {});
WorldDTO dto = response.getBody();

在我看来,错误可能是由于字段 private List&lt;CountryDTO&gt; countries; (WorldDTO.class) 没有 @JsonProperty 注释。但是json中也没有这个对象的名字。

我做错了什么?

【问题讨论】:

    标签: java json spring jackson


    【解决方案1】:

    你不需要WorldDTO 类。

    它认为你正在尝试解析一个对象

    { "countries" : [ {"id": "...", "name": ".."... ]}
    

    您应该使用ResponseEntity&lt;List&lt;CountryDTO&gt;&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-05
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多