spring boot 使用 fastjson 解析數(shù)據(jù)

spring MVC 中使用 MessageConverter 在遇到 @RequestBody 時(shí),將請求體中的 json 字符串轉(zhuǎn)換為java對象,遇到 @ResponseBody 時(shí)將方法返回值轉(zhuǎn)換為 json 字符串作為請求響應(yīng)內(nèi)容。
有時(shí)我們想要修改 json 字符串的轉(zhuǎn)換特性時(shí)(例如 null 值的處理,時(shí)間格式等) ,需要添加自定義的 MessageConverter。我平時(shí)使用 fastjson 比較多。
先來看看不用 fastjson 時(shí)的 樣子


這個(gè)接口中,并沒有返回 password 字段, 默認(rèn)的 MessageConverternull 值轉(zhuǎn)換成了 "password": null 的形式。createTime 在 java 代碼中是 date 類型,轉(zhuǎn)換成了時(shí)間戳 timestamp。

使用 fastjson

  1. 引入依賴
    之前的已經(jīng)引入了,可以跳過
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.22</version>
</dependency>
  1. 繼承 FastJsonHttpMessageConverter
    config 包中新建 FastJsonHttpMessageConverterEx.java
public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {
    public FastJsonHttpMessageConverterEx() {
        // 在這里配置 fastjson 特性
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return super.supports(clazz);
    }
}
  1. 配置 FastJsonHttpMessageConverterEx
    在 WebMvcConfigurer.java 中 Override configureMessageConverters 方法,新增內(nèi)容如下
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(fastJsonHttpMessageConverterEx());
        super.configureMessageConverters(converters);
    }

    @Bean
    public FastJsonHttpMessageConverterEx fastJsonHttpMessageConverterEx() {
        return new FastJsonHttpMessageConverterEx();
    }

配置完畢,重啟項(xiàng)目,再來添加一篇文章試試。


原本為 nullpassword 字段不見了,可見 fastjson 默認(rèn)是不轉(zhuǎn)換 null 值的。fastjson 對日期的默認(rèn)處理和spring MVC 默認(rèn)的MessageConverter一樣, createTime 還是時(shí)間戳 timestamp的格式。

配置 fastjson

接下來以轉(zhuǎn)換 null 值和換一種時(shí)間格式(yyyy-MM-dd HH:mm:ss)為例看看怎么配置 fastjson。
在 FastJsonHttpMessageConverterEx.java 的構(gòu)造方法中

    public FastJsonHttpMessageConverterEx() {
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");    // 自定義時(shí)間格式
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue); // 正常轉(zhuǎn)換 null 值
        this.setFastJsonConfig(fastJsonConfig);
    }

重啟項(xiàng)目,再次添加一篇文章試試


null 值又回來啦,createTime 也變成了我們想要的樣子。
SerializerFeature 那個(gè)類里面還有好多特性,可以點(diǎn)開看看。
在平時(shí)的開發(fā)中我比較喜歡 fastjson 默認(rèn)的配置(不顯示 null 值,使用時(shí)間戳 timestamp 表示時(shí)間),timestamp 形式的時(shí)間也方法客戶端轉(zhuǎn)換,雖然可讀性方面差了點(diǎn)。

查看項(xiàng)目完整代碼

項(xiàng)目地址: https://github.com/hyrijk/spring-boot-blog
克隆項(xiàng)目到本地

git clone https://github.com/hyrijk/spring-boot-blog.git

checkout 到當(dāng)前版本

git checkout d7365d85b21491f6746f7e08cc2ef5505751d082

完。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容