2016-03-09 83 views
0

我有一個簡單的註解類:如何序列註釋與傑克遜

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
public @interface WebService { // with methods} 

而且一個POJO

class Pojo { 
    Webservice webservice; 
} 

每當我試圖序列Pojo,各個領域得到除Webservice場序列化。

我對反序列化只有序列化不感興趣。

這是傑克遜的限制嗎?

+0

你的問題是不是序列化的註釋。對序列化感興趣但不是反序列化不計算。不清楚你要問什麼,直到沒有任何意義。 – EJP

+0

我的問題正是關於序列化註釋。 –

回答

0

一個很好的問題。如果您在批註類型方法中添加@JsonProperty批註,則序列化可以正常工作。這裏有一個例子:

@JacksonAnnotationSerialization.MyAnnotation(a = "abc", b = 123) 
public class JacksonAnnotationSerialization { 

    @Retention(RetentionPolicy.RUNTIME) 
    @interface MyAnnotation { 
     @JsonProperty 
     String a(); 
     @JsonProperty 
     int b(); 
    } 

    static class Thing { 
     public final String field; 
     public final MyAnnotation myAnnotation; 

     Thing(final String field, final MyAnnotation myAnnotation) { 
      this.field = field; 
      this.myAnnotation = myAnnotation; 
     } 
    } 

    public static void main(String[] args) throws JsonProcessingException { 
     final ObjectMapper objectMapper = new ObjectMapper(); 
     final MyAnnotation annotation 
       = JacksonAnnotationSerialization.class.getAnnotation(MyAnnotation.class); 
     final Thing thing = new Thing("value", annotation); 
     System.out.println(objectMapper.writeValueAsString(thing)); 
    } 
} 

輸出:

{"field":"value","myAnnotation":{"a":"abc","b":123}}