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
- iOS Block淺淺析iOSBloC
- 淺析 JWTJWT
- MongoDB淺析MongoDB
- RunLoop 淺析OOP
- Nginx淺析Nginx
- 淺析 requestAnimationFramerequestAnimationFrame
- 淺析PromisePromise
- 淺析GitGit
- 淺析RedisRedis
- Jvm 淺析JVM
- Webpack 原理淺析Web
- css: clip淺析CSS
- 淺析Promise原理Promise
- BTrace 原理淺析
- 淺析Java NIOJava
- 字串模板淺析字串
- 淺析 ReentrantLockReentrantLock
- HTTP Cache 淺析HTTP
- 淺析JAVA反射Java反射
- setXfermode 模式淺析模式
- AQS原理淺析AQS
- koa原理淺析
- CGLib淺析CGLib
- 淺析DES原理
- ejs 淺析JS
- AIDL淺析AI
- Fragment流程淺析Fragment
- 淺析SELinuxLinux
- IOS代理淺析iOS
- MySQL Replication淺析MySql
- web安全淺析Web
- Seata原理淺析
- InheritedWidget原理淺析
- 淺析微服務框架微服務框架
- 淺析JavaScript非同步JavaScript非同步
- canvas.drawText淺析Canvas
- Java快取淺析Java快取