没有从字符串值反序列化的字符串参数构造函数/工厂方法 \- 从 restTemplate 反序列化 json 对象时出现异常

新手上路,请多包涵

在调用以检索 json 响应并解析它时遇到问题。

 [
    {
        "name": "john doe",
        "age": "24",
        "address": "{\"state\":\"LA\",\"country\":\"US\"}"
    }
]

楷模:

人.java

 @Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    private String name;
    private String age;
    private Address address;
}

地址.java

 @Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
    private String state;
    private String country;
}

读取此数据的代码,

 ResponseEntity<List<Person>> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,requestEntity,new ParameterizedTypeReference<List<Person>>() {});

但是我得到以下异常,

RestClientException while invoking ABS ServiceError while extracting response for type [java.util.List<com.bp.model.Person>] and content type [application/json;charset=UTF-8];嵌套异常是 org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:无法构造 com.bp.model.Address 的实例(尽管至少存在一个 Creator):没有字符串参数构造函数/工厂方法可从字符串值反序列化(‘{“state”:“LA”,“country”:“US”}’);嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException:无法构造 com.bp.model.Address 的实例(尽管至少存在一个 Creator):没有字符串参数构造函数/工厂方法可以从字符串值反序列化(’ {“state”:“IN”,“brand”:“anthem”}‘) [来源: (PushbackInputStream);行:1,列:325](通过引用链:java.util.ArrayList[0]->com.bp.model.Person[“address”])

原文由 Sriram G 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 868
1 个回答

代码是正确的,但 JSON 有问题。地址是字符串而不是 JSON 对象。为了让它工作,它需要是这样的:

 "address": {"state": "LA", "country": "US"}

没有外引号和转义字符。

原文由 rph 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题