杰克逊在反序列化时抛出JsonMappingException;要求单串构造函数? [英] Jackson throws JsonMappingException on deserialize; demands single-String constructor?

查看:255
本文介绍了杰克逊在反序列化时抛出JsonMappingException;要求单串构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个问题,但它涉及到这个问题:
用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我很确定你不需要单字符串构造r,如果你这样做,你不应该填充该构造函数中的属性,对吗?

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 注释。我只是注释了我的静态创建方法,如下所示:

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;
}

然后问题解决了。

这篇关于杰克逊在反序列化时抛出JsonMappingException;要求单串构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆