Jackson - 淺析@JsonInclude
@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);
}
}
相關文章
- jackson學習之五:JsonInclude註解JSON
- 【淺度渣文】Jackson之jackson-annotations
- 【淺度渣文】Jackson之jackson-databind
- iOS Block淺淺析iOSBloC
- RunLoop 淺析OOP
- 淺析 ReentrantLockReentrantLock
- Unstated淺析
- 淺析SharedPreferences
- Nginx淺析Nginx
- 淺析PromisePromise
- ejs 淺析JS
- 淺析KubernetesStatefulSet
- AIDL淺析AI
- MongoDB淺析MongoDB
- 淺析 JWTJWT
- 淺析RedisRedis
- Jvm 淺析JVM
- ArrayList淺析
- CGLib淺析CGLib
- 淺析XMLXML
- 淺析 DDD
- koa原理淺析
- 淺析 React FiberReact
- HTTP Cache 淺析HTTP
- BTrace 原理淺析
- HashMap之淺析HashMap
- setXfermode 模式淺析模式
- 比特幣淺析比特幣
- Seata原理淺析
- 淺析AIGC for MMKGAIGC
- shadow DOM 淺析
- 淺析Promise原理Promise
- AQS原理淺析AQS
- css: clip淺析CSS
- Webpack 原理淺析Web
- InheritedWidget原理淺析
- Kubernetes Scheduler淺析
- 淺析Java NIOJava