2013-12-15 24 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

相关问题