2013-04-29 128 views
1

当我阅读使用杰克逊库从JSON这个对象忽略字段:通过使用mapper.readValue(new JsonFactory().createJsonParser(json), MyClass.class);杰克逊写

现在我想打印物体JSON

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

我解析此,使用mapper.writeValueAsString(object),但我想忽略'c'字段。我怎样才能做到这一点?在字段中添加@JsonIgnore可以防止解析时设置字段,不是吗?

回答

9

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

在反序列化时不会忽略该字段吗? – nhaarman 2013-04-29 21:02:26