JsonMappingException:没有为类型 [简单类型,类] 找到合适的构造函数:无法从 JSON 对象实例化

2022-01-13 00:00:00 json annotations spring java jackson

我在尝试获取 JSON 请求并对其进行处理时收到以下错误:

I am getting the following error when trying to get a JSON request and process it:

org.codehaus.jackson.map.JsonMappingException:没有找到适合类型 [simple type, class com.myweb.ApplesDO] 的构造函数:无法从 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:

Here is the JSON I am trying to send:

{
  "applesDO" : [
    {
      "apple" : "Green Apple"
    },
    {
      "apple" : "Red Apple"
    }
  ]
}

在Controller中,我有以下方法签名:

In Controller, I have the following method signature:

@RequestMapping("showApples.do")
public String getApples(@RequestBody final AllApplesDO applesRequest){
    // Method Code
}

AllApplesDO 是 ApplesDO 的包装器:

AllApplesDO is a wrapper of 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 对象.请帮助杰克逊将 JSON 转换为 Java 对象的配置参数.我正在使用 Spring 框架.

I think that Jackson is unable to convert JSON into Java objects for subclasses. Please help with the configuration parameters for Jackson to convert JSON into Java Objects. I am using Spring Framework.

在上述示例类中包含导致此问题的主要错误 - 请查看已接受的解决方案答案.

Included the major bug that is causing this problem in the above sample class - Please look accepted answer for solution.

推荐答案

所以,我终于意识到问题所在了.这不是我怀疑的杰克逊配置问题.

So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.

其实问题出在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
    }
}

为该类定义了一个自定义构造函数,使其成为默认构造函数.引入虚拟构造函数使错误消失:

There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:

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() {
    }

}

相关文章