2013-12-15 25 views
0

我正在嘗試用Jackson來序列化一個相當大的結構。
然而,它也試圖出口了很多子我將永遠需要的(造成JsonMappingException: No serializer found for class從序列化中排除類和名稱空間?

所以,我怎麼能排除類和命名空間的序列化?

另外,我怎麼能標記我的類屬性排除/忽略?

回答

1

如果您實際訪問要排除的子結構,請使用瞬態關鍵字。

transient是一個Java關鍵字,它標記一個成員變量不是 當它被持久化爲字節流時被序列化。當通過網絡傳輸的對象是 時,該對象需要被「序列化」。 串行化將對象狀態轉換爲串行字節。那些字節 通過網絡發送,並且從這些 字節重新創建對象。由java瞬態關鍵字標記的成員變量不是 轉移,它們有意丟失。

http://en.wikibooks.org/wiki/Java_Programming/Keywords/transient

0

請舉一個例子爲排除類和命名空間但對於您可能無法控制源代碼屬性,你可以使用類型和領域

@JsonIgnoreProperties(value = {"propertyName", "otherProperty"}) 

以下Here's the javadoc.

下面是一個例子

@JsonIgnoreProperties(value = { "name" }) 
public class Examples { 
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException { 
     Examples examples = new Examples(); 
     examples.setName("sotirios"); 
     Custom custom = new Custom(); 
     custom.setValue("random"); 
     custom.setNumber(42); 
     examples.setCustom(custom); 
     ObjectMapper mapper = new ObjectMapper(); 
     StringWriter writer = new StringWriter(); 

     mapper.writeValue(writer, examples); 
     System.out.println(writer.toString()); 
    } 

    private String name; 

    @JsonIgnoreProperties(value = { "value" }) 
    private Custom custom; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public Custom getCustom() { 
     return custom; 
    } 

    public void setCustom(Custom custom) { 
     this.custom = custom; 
    } 

    static class Custom { 
     private String value; 
     private int number; 
     public String getValue() { 
      return value; 
     } 
     public void setValue(String value) { 
      this.value = value; 
     } 
     public int getNumber() { 
      return number; 
     } 
     public void setNumber(int number) { 
      this.number = number; 
     } 
    } 
} 

打印

{"custom":{"number":42}} 

換句話說,它忽略Examples#nameCustom#value

相關問題