Jackson - 淺析@JsonInclude

aubergines發表於2020-11-03

@JsonInclude註解可用於指示何時可以對新增註解的屬性進行序列化。通常會包含屬性值,但是通過使用這個註解,我們可以基於屬性值指定簡單的排除規則。
這個註解可用於欄位,方法或建構函式引數。它也可以在類上使用,這樣對應的規則將應用於類的所有屬性。
以下是@JsonInclude定義程式碼段:

@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD,
    ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonInclude
{
   public Include value() default Include.ALWAYS;//inclusion rules
   public Include content() default Include.ALWAYS;//rules on content (e.g. Map's elements)
   public Class<?> valueFilter() default Void.class;//used for values when Include.CUSTOM
   public Class<?> contentFilter() default Void.class;//used for contents values when Include.CUSTOM 
   
   public enum Include{
       ALWAYS,//always include property
       NON_NULL,//do not include property with null value
       NON_ABSENT,//no null values including no content null values like Optional, AtomicReference etc
       NON_EMPTY,//NON_NULL + NON_ABSENT + values like empty Collections/Map/arrays/String etc are excluded
       NON_DEFAULT,//no default values, e.g. no primitives with default values  
       CUSTOM,// a custom filter for exclusion specified by JsonInclude.valueFilter()
       USE_DEFAULTS//use defaults either from class level or ObjectMapper level
       ;
   }
}
例子
定義物件
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Employee {
 	private String name;
 	private String dept;
 	private String address;
}
Main方法
    public class ExampleMain {
        public static void main(String[] args) throws IOException {
            Employee employee = Employee.of("Trish", null, null);
            ObjectMapper om = new ObjectMapper();
            String jsonString = om.writeValueAsString(employee);
            System.out.println(jsonString);
        }
    }
結果
{"name":"Trish"}

如上所示,序列化期間不包含’dept’和’address’屬性,因為我們為它們設定了null。

沒有@JsonInclude

如果我們不使用@JsonIncludeEmployee類,那麼輸出將是:

{“ name”:“ Trish”,“ dept”:null,“ address”:null}
使用ObjectMapper#setDefaultPropertyInclusion()

此方法或ObjectMapper#setSerializationInclusion()可用於全域性指定包含規則。例如,以下將產生與上面的示例相同的輸出:

public class ExampleMain {
    public static void main(String[] args) throws IOException {
        Employee employee = Employee.of("Trish", null, null);
        ObjectMapper om = new ObjectMapper();
        om.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
        String jsonString = om.writeValueAsString(employee);
        System.out.println(jsonString);
    }
}