杰克逊在写作时忽略了字段 [英] Jackson ignore fields when writing

查看:121
本文介绍了杰克逊在写作时忽略了字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用杰克逊库从JSON读取此对象:

I'm reading this object from JSON using the Jackson library:

{
    a = "1";
    b = "2";
    c = "3";
}

我正在使用 mapper.readValue解析这个(new JsonFactory()。createJsonParser(json),MyClass.class);

现在我想将对象打印到JSON,使用 mapper.writeValueAsString(object),但我想忽略'c'字段。我怎样才能做到这一点?将 @JsonIgnore 添加到字段会阻止在解析时设置字段,不是吗?

Now I want to print the object to JSON, using mapper.writeValueAsString(object), but I want to ignore the 'c' field. How can I achieve this? Adding @JsonIgnore to the field would prevent the field from being set while parsing, wouldn't it?

推荐答案

你不能通过使用公共字段来实现这一点,你必须使用方法(getter / setter)。使用Jackson 1.x,你只需要将 @JsonIgnore 添加到getter方法和没有注释的setter方法,它就可以了。杰克逊2.x,注释解决方案被重新设计,您需要在getter AND @JsonProperty 上放置 @JsonIgnore setter。

You can't do this by using public fields, you have to use methods (getter/setter). With Jackson 1.x, you simply need to add @JsonIgnore to the getter method and a setter method with no annotation, it'll work. Jackson 2.x, annotation resolution was reworked and you will need to put @JsonIgnore on the getter AND @JsonProperty on the setter.

public static class Foo {
    public String a = "1";
    public String b = "2";
    private String c = "3";

    @JsonIgnore
    public String getC() { return c; }

    @JsonProperty // only necessary with Jackson 2.x
    public String setC(String c) { this.c = c; }
}

这篇关于杰克逊在写作时忽略了字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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