最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Jackson自定義序列化與反序列化注解詳解

 更新時間:2023年11月06日 09:47:02   作者:楊小胖要減肥  
這篇文章主要介紹了Jackson自定義序列化與反序列化注解詳解,某些場景下,我們使用Jackson對數(shù)據(jù)進行序列化或反序列化的時候,需要對某些數(shù)據(jù)進行特殊處理,需要的朋友可以參考下

前言

某些場景下,我們使用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)文章

  • ActiveMQ安裝及部署教程圖解

    ActiveMQ安裝及部署教程圖解

    這篇文章主要介紹了ActiveMQ安裝及部署教程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-07-07
  • spring注解@Service注解的使用解析

    spring注解@Service注解的使用解析

    這篇文章主要介紹了spring注解@Service注解的使用解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java高級應(yīng)用之斗地主游戲

    Java高級應(yīng)用之斗地主游戲

    這篇文章主要為大家詳細介紹了Java高級應(yīng)用之斗地主游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-05-05
  • Java之SpringBoot自定義配置與整合Druid

    Java之SpringBoot自定義配置與整合Druid

    這篇文章主要介紹的是java之SpringBoot自定義配置與整合Druid的相關(guān)資料,關(guān)于SpringBoot配置文件可以是properties或者是yaml格式的文件,但是在SpringBoot加載application配置文件時是存在一個優(yōu)先級,下面小編就和大家一起進入文章學習這項知識
    2021-09-09
  • SpringCloud Gateway的基本入門和注意點詳解

    SpringCloud Gateway的基本入門和注意點詳解

    這篇文章主要介紹了SpringCloud Gateway的基本入門和注意點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 淺談序列化之protobuf與avro對比(Java)

    淺談序列化之protobuf與avro對比(Java)

    下面小編就為大家?guī)硪黄獪\談序列化之protobuf與avro對比(Java)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • Spring?Security?登錄時添加圖形驗證碼實現(xiàn)實例

    Spring?Security?登錄時添加圖形驗證碼實現(xiàn)實例

    這篇文章主要為大家介紹了Spring?Security?登錄時添加圖形驗證碼實現(xiàn)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • Springboot上傳文件的同時傳遞參數(shù)用對象接收的問題及解決方案

    Springboot上傳文件的同時傳遞參數(shù)用對象接收的問題及解決方案

    在Spring Boot中,若接口需同時接收文件和其他參數(shù),應(yīng)將文件用@RequestParam標注,其他參數(shù)封裝對象并用@Validated校驗,避免參數(shù)綁定沖突,本文給大家介紹Springboot上傳文件的同時傳遞參數(shù)用對象接收,感興趣的朋友跟隨小編一起看看吧
    2025-09-09
  • Java實現(xiàn)word文檔轉(zhuǎn)成圖片的示例詳解

    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實現(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

最新評論

绥宁县| 襄城县| 玉溪市| 明水县| 赤峰市| 吐鲁番市| 沭阳县| 石台县| 康保县| 中山市| 乌兰察布市| 新源县| 同江市| 平远县| 宜兰县| 南陵县| 芷江| 静安区| 八宿县| 繁昌县| 商河县| 石门县| 马边| 铁岭县| 广灵县| 阜新市| 新巴尔虎右旗| 平邑县| 噶尔县| 石屏县| 历史| 彝良县| 南投县| 金川县| 海口市| 鄱阳县| 高平市| 汉中市| 宜丰县| 邮箱| 长泰县|