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

Java前后端任意參數(shù)類型轉(zhuǎn)換方式(Date、LocalDateTime、BigDecimal)

 更新時間:2024年06月01日 16:29:43   作者:一恍過去  
這篇文章主要介紹了Java前后端任意參數(shù)類型轉(zhuǎn)換方式(Date、LocalDateTime、BigDecimal),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

1、前言

在前后端進(jìn)行數(shù)據(jù)交互時,對于日期往往是通過時間戳進(jìn)行交互,或者是Doule、BigDecimal等格式進(jìn)行格式化保留固定小數(shù)點(diǎn)。

比如:Double與String、BigDecimal與String、Long與Date、Long與LocalDateTime

主要通過JsonSerializerJsonDeserializer進(jìn)行實(shí)現(xiàn):

  • JsonSerializer:用于后端數(shù)據(jù)返回前端時的序列化轉(zhuǎn)換;
  • JsonDeserializer:用于前端數(shù)據(jù)請求后端時的反序列化轉(zhuǎn)換;
  • 只有請求或者響應(yīng)的實(shí)體中存定義好的轉(zhuǎn)換的類型才會進(jìn)入自定義轉(zhuǎn)換器中,比如:轉(zhuǎn)換的字段類型為BigDecimal,如果請求/響應(yīng)的實(shí)體中不包含BigDecimal類型,那么就不會進(jìn)行到轉(zhuǎn)換器中

SpringBoot中可以通過配置實(shí)現(xiàn)全局參數(shù)的字段轉(zhuǎn)換,或者使用注解標(biāo)注進(jìn)行指定字段的轉(zhuǎn)換生效或者轉(zhuǎn)換失效;

2、配置類型全局轉(zhuǎn)換器

代碼以實(shí)現(xiàn)后端格式化BigDecimal數(shù)據(jù)前后端交互LocalDateTime轉(zhuǎn)Long兩種形式進(jìn)行演示,實(shí)際中可以根據(jù)情況進(jìn)行修改轉(zhuǎn)換方式,實(shí)現(xiàn)任意類型的序列化轉(zhuǎn)換;

2.1、定義類型全局轉(zhuǎn)換器

該類中的反序列,對Get請求無效,會出現(xiàn)類型轉(zhuǎn)換失敗的情況,對于Get請求需要單獨(dú)根據(jù)定義反序列化轉(zhuǎn)換器;

DataConverterConfig:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Configuration
public class DataConverterConfig {


    /**
     * 配置消息轉(zhuǎn)換器
     *
     * @return
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            /**
             * 添加自定義消息轉(zhuǎn)換器
             */
            @Override
            public void addFormatters(FormatterRegistry registry) {
                // 對于Get請求的數(shù)據(jù)轉(zhuǎn)換
                registry.addConverter(new TimeStampToLocalDateConverter());
            }

            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
                converter.setObjectMapper(serializingObjectMapper());
                converters.add(0, converter);
            }
        };
    }

    /**
     * Serializer配置
     *
     * @return
     */
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();

        // 禁止null值字段進(jìn)行序列化
        // 如果有需要則進(jìn)行使用
        // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 添加默認(rèn)序列化,將字段轉(zhuǎn)化為轉(zhuǎn)換String,支持各種可以直接使用toString()方法的類型
        // 如果有需要則進(jìn)行開啟
        // module.addSerializer(BigInteger.class, new ToStringSerializer());
        // module.addSerializer(Long.class, new ToStringSerializer());
        // module.addSerializer(Integer.class, new ToStringSerializer());
        // module.addSerializer(BigInteger.class, new ToStringSerializer());


        // 添加自定義序列化 Serializer
        module.addSerializer(BigDecimal.class, new BigDecimalSerializer());
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        // 添加自定義反序列化 Deserializer
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(module);
        return objectMapper;
    }

    /**
     * 序列化實(shí)現(xiàn)BigDecimal轉(zhuǎn)化為String
     */
    public static class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
        @Override
        public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            String res = null;
            if (value != null) {
                int scale = value.scale();
                if (scale > 2) {
                    res = value.toString();
                } else {
                    DecimalFormat df = new DecimalFormat("#0.00");
                    res = df.format(value);
                }
                gen.writeString(res);
            }
        }
    }

    /**
     * 序列化實(shí)現(xiàn) LocalDateTime轉(zhuǎn)化為Long
     */
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            if (value != null) {
                long timestamp = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(timestamp);
            }
        }
    }

    /**
     * 反序列化實(shí)現(xiàn) Long轉(zhuǎn)化為為LocalDateTime(只對GET請求無效)
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
                throws IOException {
            long timestamp = p.getValueAsLong();
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
    }
}

2.2、定義Get請求反序列化轉(zhuǎn)換器

DataConverterConfig 類中的定義的反序列化轉(zhuǎn)換器,對Get請求無效,會出現(xiàn)類型轉(zhuǎn)換失敗的情況,對于Get請求需要單獨(dú)根據(jù)定義反序列化轉(zhuǎn)換器,比如:此處用到的Long轉(zhuǎn)LocalDateTime反序列化轉(zhuǎn)換,如果有其他類型就需要定義其他的反序列化轉(zhuǎn)換器;

TimeStampToLocalDateConverter:

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 時間戳字符串轉(zhuǎn)時間類型轉(zhuǎn)換器
 *
 */
public class TimeStampToLocalDateConverter implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(String text) {
        if (!StringUtils.isEmpty(text)) {
            long timestamp = Long.parseLong(text);
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
        return null;
    }
}

2.3、定義實(shí)體

@Data
public class Product {

    private Long id;

    private Integer num;

    private BigInteger count;

    private String name;

    private BigDecimal price;

    private BigDecimal realPrice;

    private LocalDateTime createTime;

    private Date time;
}

2.4、測試Controller

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @ApiOperation(value = "測試GET請求參數(shù)", notes = "測試POST請求參數(shù)")
    @ApiOperationSupport(order = 5)
    @GetMapping("/testGet")
    public Object testGet(Product vo) {
        System.out.println("請求參數(shù)時間:" + vo.getCreateTime());

        Product res = new Product();
        res.setId(System.currentTimeMillis());
        res.setNum(12);
        res.setCount(new BigInteger("10"));
        res.setName("測試名稱");
        res.setCreateTime(LocalDateTime.now());
        res.setPrice(new BigDecimal("12.1"));
        res.setRealPrice(new BigDecimal("12.124"));
        res.setTime(new Date());
        return res;
    }

    @ApiOperation(value = "測試POST請求參數(shù)", notes = "測試POST請求參數(shù)")
    @ApiOperationSupport(order = 10)
    @PostMapping("/testPost")
    public Product testPost(@RequestBody Product vo) {
        System.out.println("請求參數(shù)時間:" + vo.getCreateTime());

        Product res = new Product();
        res.setId(System.currentTimeMillis());
        res.setNum(12);
        res.setCount(new BigInteger("10"));
        res.setName("測試名稱");
        res.setCreateTime(LocalDateTime.now());
        res.setPrice(new BigDecimal("12.1"));
        res.setRealPrice(new BigDecimal("12.124"));
        return res;
    }
}

2.5、測試結(jié)果

1、反序列化測試

請求時對于createTime參數(shù),傳入long類型的時間戳

結(jié)果:

雖然前端傳入時參數(shù)為long類型的時間戳,但是后端打印出的數(shù)據(jù)格式為LocalDateTime,表示反序列化是轉(zhuǎn)換成功;

2、序列化測試

響應(yīng)參數(shù)定義如下:

前端結(jié)果:

可以看出,在后端定義的實(shí)體中createTime字段的類型為LocalDateTime,price字段的值是12.1只有一位小數(shù);

當(dāng)響應(yīng)到前端時createTime字段的值時Long類型的時間戳,price字段的值為12.10并且是保留兩位小數(shù)的String類型值。

3、WebMvcConfigurationSupport踩坑說明

如果項(xiàng)目中存在繼承WebMvcConfigurationSupport的配置類,那么在定義DataConverterConfig(全局轉(zhuǎn)換器)時的配置就需要做出調(diào)整,調(diào)整如下:

1、DataConverterConfig修改處理

DataConverterConfig中刪除WebMvcConfigurer webMvcConfigurer()方法,對ObjectMapper serializingObjectMapper()方法加上@Bean注解,更改后代碼如下:

@Configuration
public class DataConverterConfig {	
    /**
     * Serializer配置
     *
     * @return
     */
    @Bean
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        // 添加自定義序列化 Serializer
        module.addSerializer(BigDecimal.class, new BigDecimalSerializer());
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        // 添加自定義反序列化 Deserializer
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(module);
        return objectMapper;
    }

    /**
     * 序列化實(shí)現(xiàn)BigDecimal轉(zhuǎn)化為String
     */
    public static class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
        @Override
        public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            String res = null;
            if (value != null) {
                int scale = value.scale();
                if (scale > 2) {
                    res = value.toString();
                } else {
                    DecimalFormat df = new DecimalFormat("#0.00");
                    res = df.format(value);
                }
                gen.writeString(res);
            }
        }
    }

    /**
     * 序列化實(shí)現(xiàn) LocalDateTime轉(zhuǎn)化為Long
     */
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            if (value != null) {
                long timestamp = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(timestamp);
            }
        }
    }

    /**
     * 反序列化實(shí)現(xiàn) Long轉(zhuǎn)化為為LocalDateTime(只對GET請求無效),對于GET請求需要單獨(dú)訂單轉(zhuǎn)換器,比如:TimeStampToLocalDateConverter
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
                throws IOException {
            long timestamp = p.getValueAsLong();
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
    }
}

2、WebMvcConfigurationSupport繼承類中處理

WebMvcConfigurationSupport繼承類中新增addFormatters()方法與extendMessageConverters方法以及注入ObjectMapper,更改后代碼如下:

@Configuration
public class WebMvcRegistrationsConfig extends WebMvcConfigurationSupport {
    @Resource
    private ObjectMapper serializingObjectMapper;

    /**
     * 添加自定義消息轉(zhuǎn)換器
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        // 添加時間戳轉(zhuǎn)日期類型消息轉(zhuǎn)換器
        registry.addConverter(new TimeStampToLocalDateConverter());
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(serializingObjectMapper);
        converters.add(0, converter);
    }
}

總結(jié)

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java設(shè)計模式中橋接模式應(yīng)用詳解

    Java設(shè)計模式中橋接模式應(yīng)用詳解

    橋接,顧名思義,就是用來連接兩個部分,使得兩個部分可以互相通訊。橋接模式將系統(tǒng)的抽象部分與實(shí)現(xiàn)部分分離解耦,使他們可以獨(dú)立的變化。本文通過示例詳細(xì)介紹了橋接模式的原理與使用,需要的可以參考一下
    2022-11-11
  • springboot使用單元測試實(shí)戰(zhàn)

    springboot使用單元測試實(shí)戰(zhàn)

    這篇文章主要介紹了springboot使用單元測試實(shí)戰(zhàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-09-09
  • 詳解Java中的時區(qū)類TimeZone的用法

    詳解Java中的時區(qū)類TimeZone的用法

    TimeZone可以用來獲取或者規(guī)定時區(qū),也可以用來計算時差,這里我們就來詳解Java中的時區(qū)類TimeZone的用法,特別要注意下面所提到的TimeZone相關(guān)的時間校準(zhǔn)問題.
    2016-06-06
  • Spring中ApplicationListener的使用解析

    Spring中ApplicationListener的使用解析

    這篇文章主要介紹了Spring中ApplicationListener的使用解析,ApplicationContext事件機(jī)制是觀察者設(shè)計模式的實(shí)現(xiàn),通過ApplicationEvent類和ApplicationListener接口,需要的朋友可以參考下
    2023-12-12
  • Java NIO寫大文件對比(win7和mac)

    Java NIO寫大文件對比(win7和mac)

    這篇文章主要介紹了Java NIO寫大文件對比(win7和mac),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • 淺析Java SPI 與 dubbo SPI

    淺析Java SPI 與 dubbo SPI

    在Java中SPI是被用來設(shè)計給服務(wù)提供商做插件使用的。本文重點(diǎn)給大家介紹Java SPI 與 dubbo SPI的相關(guān)知識及區(qū)別介紹,感興趣的朋友跟隨小編一起學(xué)習(xí)下吧
    2021-05-05
  • Java使用hutool實(shí)現(xiàn)文件大小的友好輸出

    Java使用hutool實(shí)現(xiàn)文件大小的友好輸出

    這篇文章主要為大家詳細(xì)介紹了Java如何使用hutool實(shí)現(xiàn)文件大小的友好輸出,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解下
    2023-11-11
  • SpringBoot請求與響應(yīng)實(shí)例全解析

    SpringBoot請求與響應(yīng)實(shí)例全解析

    文章主要介紹了SpringBoot中請求與響應(yīng)的處理方式,包括簡單參數(shù)、實(shí)體參數(shù)、數(shù)組集合參數(shù)、日期參數(shù)、JSON參數(shù)和路徑參數(shù)的處理,同時,還介紹了響應(yīng)的處理,包括@ResponseBody注解和統(tǒng)一響應(yīng)結(jié)果類的設(shè)計
    2026-04-04
  • Mybatis中sql映射文件中的增刪查改

    Mybatis中sql映射文件中的增刪查改

    本文主要介紹了Mybatis中sql映射文件中的增刪查改,包括創(chuàng)建數(shù)據(jù)表、配置Maven項(xiàng)目、編寫實(shí)體類和接口,以及mapper映射文件的增刪查改操作,具有一定的參考價值,感興趣的可以了解一下
    2025-10-10
  • SpringBoot 多Profile使用與切換方式

    SpringBoot 多Profile使用與切換方式

    這篇文章主要介紹了SpringBoot 多Profile使用與切換方式,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04

最新評論

北川| 汉川市| 柳林县| 邛崃市| 班戈县| 师宗县| 石柱| 玛纳斯县| 揭阳市| 衡阳市| 济阳县| 定南县| 仙居县| 新闻| 田东县| 许昌县| 扎鲁特旗| 静宁县| 太康县| 灵丘县| 镇远县| 绵阳市| 密山市| 洛隆县| 伊金霍洛旗| 蓝山县| 乳源| 东山县| 轮台县| 安乡县| 大化| 金山区| 尉氏县| 苍梧县| 华亭县| 女性| 海伦市| 平邑县| 周口市| 新兴县| 渝中区|