2015-04-25 54 views
3

是否有傑克遜爲註釋字段和/或吸氣忽略除了那些列出的字段的值的所有屬性?傑克遜場註解,忽略所有特性,但這些上市

當應用於場,不同之處在於代替包括所有但列出的屬性,這將排除所有但列出的屬性這就像@JsonIgnoreProperties

例如,如果註釋被命名爲@JsonIncludeProperties

class A { 
    final int a = 1; 
    final int b = 1; 
    ... // final int c = 1; through final int y = 1; 
    final int z = 1; 
} 

class B { 
    @JsonProperty 
    @JsonIncludeProperties({"m", "o"}) 
    A a1; 
    @JsonProperty 
    A a2; 
} 

將序列到:

{ 
    "a1": { 
     "m": 1, 
     "o": 1 
    }, 
    "a2": { 
     "a": 1, 
     "b": 1, 
     ... // "c": 1, through "y": 1, 
     "z": 1 
    } 
} 
+0

'@ JsonAutoDetect'可能有不同的設置? – Marvin

+0

感謝您的建議,但是,據我所知,'@ JsonAutoDetect'絕不會幫我。我需要爲不同的領域,其類型爲'A'過濾器類的'屬性A'不同。 IIRC,'@ JsonAutoDetect'只能在類級別,所以它不能在不同的地方不同的過濾同一類的屬性。 – XDR

回答

2

可以使用the Jackson filters和一個自定義的註釋實現。這裏是一個例子:

public class JacksonIncludeProperties { 
    @Retention(RetentionPolicy.RUNTIME) 
    @interface JsonIncludeProperties { 
     String[] value(); 
    } 

    @JsonFilter("filter") 
    @JsonIncludeProperties({"a", "b1"}) 
    static class Bean { 
     @JsonProperty 
     public final String a = "a"; 
     @JsonProperty("b1") 
     public final String b = "b"; 
     @JsonProperty 
     public final String c = "c"; 
    } 

    private static class IncludePropertiesFilter extends SimpleBeanPropertyFilter { 

     @Override 
     protected boolean include(final PropertyWriter writer) { 
      final JsonIncludeProperties includeProperties = 
        writer.getContextAnnotation(JsonIncludeProperties.class); 
      if (includeProperties != null) { 
       return Arrays.asList(includeProperties.value()).contains(writer.getName()); 
      } 
      return super.include(writer); 
     } 
    } 

    public static void main(String[] args) throws JsonProcessingException { 
     final ObjectMapper objectMapper = new ObjectMapper(); 
     final SimpleFilterProvider filterProvider = new SimpleFilterProvider(); 
     filterProvider.addFilter("filter", new IncludePropertiesFilter()); 
     objectMapper.setFilters(filterProvider); 
     System.out.println(objectMapper.writeValueAsString(new Bean())); 
    } 
}