【发布时间】:2015-08-19 14:44:43
【问题描述】:
我正在使用休息模板获取 json
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
test = restTemplate.getForObject(url,Test.class, params);
我得到像 json 一样的
{"object":"{\"id\":123,\"userId\":159,\"contentId\":1}"}
这是我的 POJO
@JsonIgnoreProperties(ignoreUnknown = true)
public class Test {
@JsonProperty("id")
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
但我遇到了错误
[Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@9bd513b; line: 1, column: 75] (through reference chain: nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.soham.Test] from String value ('{"id":123,"userId":116,"contentId":0}'); no single-String constructor/factory method
更新: 我试图添加一个构造函数
public Test(String id){
this.id=id;
}
然后它没有显示错误。但是它正在打印整个 json
{"id":123,"userId":116,"contentId":0}
如何解决?有什么想法吗?
【问题讨论】:
-
错误消息说明我猜很清楚 - 此外,这里有很多重复项,例如 this f.e
-
@RomanVottner 查看我的更新答案。但是您提到的问题没有接受的答案
-
你可以试试this approach
-
@RomanVottner 。我希望它可以通过 POJO 映射。我想避免使用 objectMapper
-
看来你应该添加一个wrapper class
标签: java json jackson spring-boot