杰克逊在写作时无视字段

nha*_*man 4 java jackson

我正在使用Jackson库从JSON读取此对象:

{
    a = "1";
    b = "2";
    c = "3";
}
Run Code Online (Sandbox Code Playgroud)

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

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

Pas*_*nas 12

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

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; }
}
Run Code Online (Sandbox Code Playgroud)