如何将JSON null反序列化为NullNode而不是Java null?

时间:2013-03-08 12:09:34

标签: java jackson

注:Jackson 2.1.x。

问题很简单但到目前为止我找不到解决方案。我浏览了现有的文档等,但找不到答案。

基类是这样的:

@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "op")

@JsonSubTypes({
    @Type(name = "add", value = AddOperation.class),
    @Type(name = "copy", value = CopyOperation.class),
    @Type(name = "move", value = MoveOperation.class),
    @Type(name = "remove", value = RemoveOperation.class),
    @Type(name = "replace", value = ReplaceOperation.class),
    @Type(name = "test", value = TestOperation.class)
})

public abstract class JsonPatchOperation
{
    /*
     * Note: no need for a custom deserializer, Jackson will try and find a
     * constructor with a single string argument and use it
     */
    protected final JsonPointer path;

    protected JsonPatchOperation(final JsonPointer path)
    {
        this.path = path;
    }

    public abstract JsonNode apply(final JsonNode node)
        throws JsonPatchException;

    @Override
    public String toString()
    {
        return "path = \"" + path + '"';
    }
}

有问题的课是:

public abstract class PathValueOperation
    extends JsonPatchOperation
{
    protected final JsonNode value;

    protected PathValueOperation(final JsonPointer path, final JsonNode value)
    {
        super(path);
        this.value = value.deepCopy();
    }

    @Override
    public String toString()
    {
        return super.toString() + ", value = " + value;
    }
}

当我尝试反序列化时:

{ "op": "add", "path": "/x", "value": null }

我希望将null值反序列化为NullNode,而不是Java null。到目前为止,我找不到办法。

你是如何实现这一目标的?

(注意:具体类的所有构造函数都是@JsonCreator,带有适当的@JsonProperty注释 - 它们没有问题,我唯一的问题是JSON null处理)

1 个答案:

答案 0 :(得分:5)

好吧,我没有阅读足够的文档,事实上它非常简单。

JsonDeserializer的{​​{3}}实现,您可以扩展。 JsonDeserializer有一个JsonNodeDeserializer

因此,自定义反序列化程序是有序的:

public final class JsonNullAwareDeserializer
    extends JsonNodeDeserializer
{
    @Override
    public JsonNode getNullValue()
    {
        return NullNode.getInstance();
    }
}

而且,在有问题的课程中:

@JsonDeserialize(using = JsonNullAwareDeserializer.class)
protected final JsonNode value;