Jackson自定義序列化與反序列化注解詳解
前言
某些場景下,我們使用Jackson對數(shù)據(jù)進行序列化或反序列化的時候,需要對某些數(shù)據(jù)進行特殊處理,比如,不同的場景下,對數(shù)字的精度要求不同,此時如果僅僅使用原始的@JsonDeserialize和@JsonSerialize注解,不能滿足我們的需求,如果每種精度都寫一個獨立的處理類,無疑增加了代碼的復(fù)雜度。
我們可以看到@JsonDeserialize和@JsonSerialize都支持注解標注
于是可以自己定義一個注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JsonDeserialize(using = DecimalFormatJsonDeserializer.class)
public @interface DecimalFormat{
int scale() default 2;
}
僅僅加上@JsonDeserialize注解的話,會發(fā)現(xiàn)Jackson在反序列時,并不會走到我們定義的DecimalFormatJsonDeserializer類中,還需要加上一個Jackson的注解繼承注解@JacksonAnnotationsInside
自定義反序列化注解及實現(xiàn)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonDeserialize(using = DecimalFormatJsonDeserializer.class)
public @interface DecimalFormat{
int scale() default 2;
}
編寫反序列化實現(xiàn)
public static class DecimalFormatJsonDeserializer extends JsonDeserializer<Double> {
@Override
public Double deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
// 獲取當前反序列化的對象類型
Class<?> clazz = jsonParser.getCurrentValue().getClass();
BigDecimal decimalValue = jsonParser.getDecimalValue();
Field declaredField;
try {
// 通過字段名稱獲取對應(yīng)字段
// 需考慮繼承情況
declaredField = clazz.getDeclaredField(jsonParser.getCurrentName());
} catch (NoSuchFieldException e) {
return decimalValue.doubleValue();
}
// 獲取注解
DecimalFormat annotation = declaredField.getAnnotation(DecimalFormat.class);
if (annotation == null) {
return decimalValue.doubleValue();
}
int scale = annotation.scale();
if (decimalValue != null) {
return decimalValue.setScale(scale, RoundingMode.HALF_UP).doubleValue();
}
return null;
}
}
測試代碼
@Data
static class TestVo {
@DecimalFormat(scale = 1)
private Double amount;
private String name;
}
public static void main(String args[]) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
TestVo testVo = objectMapper.readValue("{\"amount\":3.5576,\"name\":\"young\"}", TestVo.class);
System.out.println(testVo); // TestVo(amount=3.6, name=young)
}
自定義序列化注解及實現(xiàn)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = DecimalFormatJsonSerializer.class)
public @interface DecimalSerializerFormat {
String pattern() default "0.0000";
}
編寫序列化實現(xiàn)
public class DecimalFormatJsonSerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
JsonStreamContext outputContext = jsonGenerator.getOutputContext();
// 獲取當前class對象
Class<?> clazz = outputContext.getCurrentValue().getClass();
// 獲取當前屬性名
String fieldName = outputContext.getCurrentName();
// 獲取當前屬性的field
Field field = FieldUtils.getDeclaredField(clazz, fieldName, true);
// 獲取當前屬性的注解
DecimalSerializerFormat annotation = field.getAnnotation(DecimalSerializerFormat.class);
if (annotation == null) {
return;
}
String pattern = annotation.pattern();
DecimalFormat decimalFormat = new DecimalFormat(pattern);
jsonGenerator.writeString(decimalFormat.format(bigDecimal));
}
}
測試代碼
public static void main(String[] args) throws JsonProcessingException {
Test test = new Test();
test.setDecimal(BigDecimal.ONE);
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(test);
System.out.println(s); // {"decimal":"1.0000"}
}
@Data
static class Test{
@DecimalSerializerFormat
private BigDecimal decimal;
}
到此這篇關(guān)于Jackson自定義序列化與反序列化注解詳解的文章就介紹到這了,更多相關(guān)Jackson序列化與反序列化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringCloud Gateway的基本入門和注意點詳解
這篇文章主要介紹了SpringCloud Gateway的基本入門和注意點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
Spring?Security?登錄時添加圖形驗證碼實現(xiàn)實例
這篇文章主要為大家介紹了Spring?Security?登錄時添加圖形驗證碼實現(xiàn)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
Springboot上傳文件的同時傳遞參數(shù)用對象接收的問題及解決方案
在Spring Boot中,若接口需同時接收文件和其他參數(shù),應(yīng)將文件用@RequestParam標注,其他參數(shù)封裝對象并用@Validated校驗,避免參數(shù)綁定沖突,本文給大家介紹Springboot上傳文件的同時傳遞參數(shù)用對象接收,感興趣的朋友跟隨小編一起看看吧2025-09-09
Java實現(xiàn)word文檔轉(zhuǎn)成圖片的示例詳解
本文主要為大家詳細介紹了如何在Java項目中引用aspose-words和poi-tljar包實現(xiàn)word文檔轉(zhuǎn)成圖片,感興趣的小伙伴可以跟隨小編一起學習一下2024-10-10
一文詳解如何配置MyBatis實現(xiàn)打印可執(zhí)行的SQL語句
在MyBatis中,動態(tài)SQL是一個強大的特性,允許我們在XML映射文件或注解中編寫條件語句,根據(jù)運行時的參數(shù)來決定SQL的具體執(zhí)行內(nèi)容,這篇文章主要給大家介紹了關(guān)于如何配置MyBatis實現(xiàn)打印可執(zhí)行的SQL語句的相關(guān)資料,需要的朋友可以參考下2024-08-08

