【发布时间】:2015-01-23 20:05:29
【问题描述】:
我正在尝试使用 Jackson 对对象进行去耳化
this.prepareCustomMapper().readValue(response.getBody(), EmailResponse.class);
我有这个例外:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.despegar.social.automation.services.emailservice.response.EmailResponse]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader@4f38f663; line: 1, column: 12] (through reference chain: com.despegar.social.automation.services.emailservice.response.EmailsResponse["items"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
我知道这是因为这是我的构造函数:
public class EmailResponse extends MyServiceResponse {
private String id;
private String user_id;
private String email;
private Boolean is_primary;
private Boolean is_confirmed;
public EmailResponse(HttpResponse request) {
super(request);
}
}
所以,我的构造函数接收到 HttpResponse 参数并且我没有传递它,但我不知道该怎么做。我不能用空的构造函数多收费,因为我需要它以这种方式接收 HttpResponse 对象。 当我调用 readValue() 方法时,有什么方法可以传递这个构造函数参数吗?或者在这种情况下最好的选择是什么?我感谢您的帮助。问候
【问题讨论】:
-
我不能用空的构造函数多收费,因为我需要它以这种方式接收 HttpResponse 对象:你为什么不能保留你已经拥有的构造函数,并添加另一个构造函数没有争论?这就是平均加载。
-
因为它必须通过构造函数接收 HttpResponse 对象。如果我创建一个空的构造函数,我将不得不创建 setter 方法来输入 HttpResponse 而我不想这样做。是不是可以告诉杰克逊在解散期间在构造函数中使用什么参数?
-
这里有一些 JSON:{"foo":"bar"}。你要求 JSON 解组它。为什么要使用 HttpResponse?它会在哪里找到它?这就是你要找的东西:fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/…?
-
我只想将 HttpResponse 对象存储到 EmailResponse 中(我在代码的另一部分需要 HttpResponse 数据),但我不想在 EmailResponse 类中创建公共设置方法,并受保护或“无修饰符”也不是选项,所以我认为可行的唯一方法是通过构造函数传递它。我知道它有点复杂:P 但无论如何谢谢
标签: java json serialization mapping jackson