java Jackson ObjectMapper 无法反序列化 POJO,引发异常:找不到适合类型 [...] 的构造函数:无法从 JSON 对象实例化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12916774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson ObjectMapper cannot deserialize POJO, throws an exception: No suitable constructor found for type [...]: can not instantiate from JSON object
提问by tribbloid
I have tried to test the following code with no success:
我试图测试以下代码但没有成功:
class TestClass
{
private class ND2Customer
{
public String name;
public String description;
public String email;
public Boolean multiuser;
public String dnszone;
public String uri;
public String type;
public ND2Customer()
{
}
}
@Test
public void TestHymanson() throws JsonParseException, JsonMappingException, IOException
{
String json="{\"description\": \"test1u\", \"dnszone\": \"test1.public.sevenltest.example.com.\", \"uri\": \"http://199.127.129.69/customer/test1\", \"multiuser\": true, \"type\": \"2.0.3-3146\", \"email\": \"[email protected]\", \"name\": \"test1\"}";
ObjectMapper mapper = new ObjectMapper();
ND2Customer casted=mapper.readValue(json, ND2Customer.class);
String castedback=mapper.defaultPrettyPrintingWriter().writeValueAsString(casted);
System.out.println(castedback);
}
}
This problem is different from this one: Deserializing JSON with Hymanson - Why JsonMappingException "No suitable constructor"?
这个问题与这个问题不同: Deserializing JSON with Hymanson - Why JsonMappingException "No合适的构造函数"?
and this one: JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object
还有这个: JsonMappingException:找不到适合类型 [简单类型,类] 的构造函数:无法从 JSON 对象实例化
and this one: JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object
还有这个: JsonMappingException:找不到适合类型 [简单类型,类] 的构造函数:无法从 JSON 对象实例化
as I have manually override the default constructor, and its not a subclass.
因为我手动覆盖了默认构造函数,它不是子类。
How do I fix this problem?
我该如何解决这个问题?
回答by eugen
Make it static. Hymanson can not deserialize to inner classes
让它静态。Hymanson 不能反序列化到内部类
回答by Donal Fellows
The problem is probably that Hymanson can't properly reach your ND2Customer
class to invoke its constructor because it is private
, as your class otherwise looks just fine. Try making it public
and seeing if that works.
问题可能是 Hymanson 无法正确访问您的ND2Customer
类以调用其构造函数,因为它是private
,因为您的类在其他方面看起来很好。尝试制作它public
,看看它是否有效。