本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
Jackson转换JSON数据到对象类型报错?
后台有一个接收JSON数据的接口,但是当我请求这个接口后,报了如下错误:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.myweb.ApplesDO]: can not instantiate from JSON object (need to add/enable type information?)
复制代码
这是我要发送的JSON数据
{
"applesDO" : [
{
"apple" : "Green Apple"
},
{
"apple" : "Red Apple"
}
]
}
复制代码
在Controller
中我有如下方法声明
@RequestMapping("showApples.do")
public String getApples(@RequestBody final AllApplesDO applesRequest){
// Method Code
}
复制代码
AllApplesDo
对ApplesDo
进行了封装
public class AllApplesDO {
private List<ApplesDO> applesDO;
public List<ApplesDO> getApplesDO() {
return applesDO;
}
public void setApplesDO(List<ApplesDO> applesDO) {
this.applesDO = applesDO;
}
}
复制代码
下面是ApplesDo
的源码
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String appl) {
this.apple = apple;
}
public ApplesDO(CustomType custom){
//constructor Code
}
}
复制代码
我想Jackson是否无法把JSON直接转化成Java对象呢?
回答一
最终,我终于找到了问题所在,这并不是我怀疑的Jackson配置问题,实际上问题出在ApplesDo
类中:
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom) {
//constructor Code
}
}
复制代码
这个类中定义了一个有参构造函数,因此,默认的无参构造就无法使用了,这就导致了错误。
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom) {
//constructor Code
}
//Introducing the dummy constructor
public ApplesDO() {
}
}
复制代码
回答二
我想给这个问题另一个解法,并不需要新建一个虚拟无参构造方法,我们可以通过注解来让jackson确定构造函数参数和字段之间的映射。
所以下面的示例也是可用的,注意注解中的字符串必须与字段名匹配。
import com.fasterxml.jackson.annotation.JsonProperty;
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public ApplesDO(CustomType custom){
//constructor Code
}
public ApplesDO(@JsonProperty("apple")String apple) {
}
}
复制代码
文章翻译自Stack Overflow:stackoverflow.com/questions/7…
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END