Jackson 在反序列化时抛出 JsonMappingException;需要单字符串构造函数? [英] Jackson throws JsonMappingException on deserialize; demands single-String constructor?
问题描述
另一个问题,但它与这个问题有关:使用 Jackson 反序列化 JSON - 为什么 JsonMappingException 没有合适的构造函数"?
Another question, but it relates to this one: Deserializing JSON with Jackson - Why JsonMappingException "No suitable constructor"?
这次我遇到了一个不同的错误,即 Jackson 反序列化器抱怨我的类 ProtocolContainer 中没有单字符串构造函数/工厂方法".
This time I am getting a different error, namely that the Jackson deserializer complains that I do not have a "single-String constructor/factory method" in my class ProtocolContainer.
但是,如果我添加一个单字符串构造函数,如下所示:
However, if I add a single-String constructor, like this:
public ProtocolContainer(String json) {}
异常确实消失了,但是我期望的 ProtocolContainer
全是空的",即它的所有属性都处于初始状态,而不是根据 JSON 字符串填充.
the exception does indeed disappear, but the ProtocolContainer
that I expected to be there is all "empty", i.e. all its properties are in their initial state, and not populated according to the JSON-string.
这是为什么?
我很确定您不应该需要单字符串构造函数,如果这样做,您就不必在该构造函数中填充属性,对吗?
I'm pretty sure you shouldn't need a single-String constructor, and if you do that you should not have to populate the properties in that constructor, right?
=)
推荐答案
哦,所以我在发布这个问题后再次找到了答案(尽管我在发布之前尝试了很多东西).
Oh, so once again I found out the answer AFTER I posted this question (even though I tried a lot of things before posting).
我为解决这个问题所做的是使用 @JsonCreator
注释.我只是注释了我的静态 Create
方法,如下所示:
What I did to solve this was to use the @JsonCreator
annotation. I simply annotated my static Create
method, like this:
@JsonCreator
public static ProtocolContainer Create(String jsonString)
{
ProtocolContainer pc = null;
try {
pc = mapper.readValue(jsonString, ProtocolContainer.class);
} catch (JsonParseException|JsonMappingException|IOException e) {
// handle
}
return pc;
}
然后问题就解决了.
这篇关于Jackson 在反序列化时抛出 JsonMappingException;需要单字符串构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!