問題描述
我在嘗試獲取 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] 的構造函數(shù):無法從 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?)
這是我要發(fā)送的 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 對象的配置參數(shù).我正在使用 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
}
}
為該類定義了一個自定義構造函數(shù),使其成為默認構造函數(shù).引入虛擬構造函數(shù)使錯誤消失:
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() {
}
}
這篇關于JsonMappingException:沒有為類型 [簡單類型,類] 找到合適的構造函數(shù):無法從 JSON 對象實例化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!