杰克逊在写作时无视字段

时间:2013-04-29 20:38:57

标签: java jackson

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

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

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

解析此问题

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

2 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分: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);
相关问题