2011-07-07 21 views
0

我正在使用JSON Jackson將POJO轉換爲JSON。我使用如何控制使用Jackson JSON時序列化哪些實例變量

mapper.writeValueAsString(s); 

這是工作的罰款。問題是我不想將所有類的變量轉換爲JSON。任何人都知道如何做到這一點;是否有任何功能ObjectMapper其中我們可以指定不要將此類可變成JSON

+1

什麼是「類變量」?一個領域? – skaffman

+0

我猜這實際上並不是指靜態字段,因爲默認情況下,Jackson不會序列化靜態字段。 –

回答

3

@JsonIgnoreJavaDoc)註釋要忽略的字段。

1

以下是使用@JsonIgnore@JsonIgnoreType來忽略特定屬性或忽略特定類型的所有屬性的示例。

import org.codehaus.jackson.annotate.JsonIgnore; 
import org.codehaus.jackson.annotate.JsonIgnoreType; 
import org.codehaus.jackson.map.ObjectMapper; 

public class JacksonIgnoreFieldsDemo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    ObjectMapper mapper = new ObjectMapper(); 

    String json1 = mapper.writeValueAsString(new Bar()); 
    System.out.println(json1); // {"a":"A"} 

    // input: {"a":"xyz","b":"B"} 
    String json2 = "{\"a\":\"xyz\",\"b\":\"B\"}"; 
    Bar bar = mapper.readValue(json2, Bar.class); 
    System.out.println(bar.a); // xyz 
    System.out.println(bar.b); // B 

    System.out.println(); 
    System.out.println(mapper.writeValueAsString(new BarContainer())); 
    // output: {"c":"C"} 
    } 
} 

class BarContainer 
{ 
    public Bar bar = new Bar(); 
    public String c = "C"; 
} 

@JsonIgnoreType 
class Bar 
{ 
    public String a = "A"; 
    @JsonIgnore 
    public String b = "B"; 
} 

更多選擇在我的博客文章在http://programmerbruce.blogspot.com/2011/07/gson-v-jackson-part-4.html


更新糾正複製 - 粘貼錯誤的概述。

相關問題