我在尝试获取JSON请求并处理它时收到以下错误:
org.codehaus.jackson.map.JsonMappingException:找不到类型[simple type,class com.myweb.ApplesDO]的合适构造函数:无法从JSON对象实例化(需要添加/启用类型信息?)
这是我要发送的JSON:
{
"applesDO" : [
{
"apple" : "Green Apple"
},
{
"apple" : "Red Apple"
}
]
}
Run Code Online (Sandbox Code Playgroud)
在Controller中,我有以下方法签名:
@RequestMapping("showApples.do")
public String getApples(@RequestBody final AllApplesDO applesRequest){
// Method Code
}
Run Code Online (Sandbox Code Playgroud)
AllApplesDO是ApplesDO的包装器:
public class AllApplesDO {
private List<ApplesDO> applesDO;
public List<ApplesDO> getApplesDO() {
return applesDO;
}
public void setApplesDO(List<ApplesDO> applesDO) {
this.applesDO = applesDO;
}
}
Run Code Online (Sandbox Code Playgroud)
ApplesDO:
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String appl) { …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Jackson来读取/写入我的POJO来自Json.截至目前,除了第三方课程外,我已经为我的课程配置并工作了.当试图读入Json我得到错误:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type
Run Code Online (Sandbox Code Playgroud)
经过一些快速的谷歌搜索后,似乎我的类需要一个默认的构造函数或覆盖带注释的默认构造函数.不幸的是,失败的类来自第三方库,并且该类没有默认构造函数,我显然无法覆盖代码.
所以我的问题是,我能做些什么或者我运气不好吗?
谢谢.
该类ResponseEntity 没有默认构造函数。然后,为了使用 objectMapper 反序列化它,我决定使用 araqnid 在该答案中给出的方法。很快 - 它需要使用 Jackson 的 mixin 功能和 @JsonCreator。
就我而言(使用 ResponseEntity),由于不同的原因,它还没有解决。
我的测试方法如下所示:
public static void main(String[] args) throws Exception {
ResponseEntity<Object> build = ResponseEntity.ok().build();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(ResponseEntity.class, ResponseEntityMixin.class);
String s = objectMapper.writeValueAsString(build);
ResponseEntity<Object> result = objectMapper.readValue(s, ResponseEntity.class);
System.out.println(result);
}
Run Code Online (Sandbox Code Playgroud)
首先,我尝试使用最短的 mixin 构造函数:
public abstract static class ResponseEntityMixin {
@JsonCreator
public ResponseEntityMixin(@JsonProperty("status") HttpStatus status) {
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我收到一个断言错误,因为ResponseEntity它的构造函数中有这行代码:
Assert.notNull(status, "HttpStatus must not be null");
Run Code Online (Sandbox Code Playgroud)
然后我将@JsonCreator的模式切换为,DELEGATING但在这种情况下我得到了另一个异常:
Exception …Run Code Online (Sandbox Code Playgroud)