4

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

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

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

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

4

2 回答 2

12

您不能通过使用公共字段来做到这一点,您必须使用方法(getter/setter)。使用 Jackson 1.x,您只需添加@JsonIgnore到 getter 方法和不带注释的 setter 方法,它就可以工作。Jackson 2.x,注释解析被重新设计,您需要将@JsonIgnoregetter 和@JsonPropertysetter 放在一起。

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; }
}
于 2013-04-30T17:01:52.350 回答
0

您可以@JsonIgnoreProperties({"c"})在序列化对象时使用。

@JsonIgnoreProperties({"c"})
public static class Foo {
    public String a = "1";
    public String b = "2";
    public String c = "3";
}

//Testing
ObjectMapper mapper = new ObjectMapper();
Foo foo = new Foo();
foo.a = "1";
foo.b = "2";
foo.c = "3";
String out = mapper.writeValueAsString(foo);
Foo f = mapper.readValue(out, Foo.class);
于 2013-04-29T21:00:06.723 回答