spring,springBoot配置類型轉化器Converter以及FastJsonHttpMessageConverter,StringHttpMessageConverter 使用


轉載請注明出處: 

  https://i.cnblogs.com/posts/edit;postId=14045507

 

spring,spring boot 等框架項目通過@RequestBody,@ResponseBody 完成請求報文到響應對象及響應對象到響應報文的轉換,其底層是通過

消息轉換器完成消息之間的轉換,包括格式轉化,類型轉化等。比如返回JSON數據或XML數據等。

  spring 默認有很多消息類型轉換器:

    MappingJackson2XmlHttpMessageConverter 基於Jackson的XML轉換器,能夠將對象轉換成XML格式的數據
    MappingJackson2HttpMessageConverter 基於 Jackson 的JSON轉換器,能夠將對象轉換成JSON格式的數據
    GsonHttpMessageConverter 基於Gson的JSON轉換器,能夠將對象轉換成JSON格式數據

  對於系統中默認包含的轉換器,只要我們在項目中加入轉換器所依賴的JAR包,相關轉換器就會被加載。

@RequestMapping(value="/json", produces={"application/json; charset=UTF-8"})

  使用@RequestMapping設置的路徑設置為 value屬性的值,此外另外設置一個屬性 produces,這個屬性接受一個字符串數組。接受的數據類型是 media type。上面這個例子就是標明這個方法的返回結果要轉換成UTF-8編碼的JSON數據。

  SpringMVC在項目初始化時,會去掃描系統中的JAR包,然后根據掃描到的JAR包設置默認的轉換類型,大概的掃描過程是:
    1)檢查系統中是否存在jackson-xml的JAR包,如果存在,就將數據轉換類型列表中設置XML類型,以及其對應的轉換器
    2)檢查系統中是否存在jackson-json的JAR包,如果存在,就在數據轉換類型列表中設置JSON類型,以及其對應的轉換器

  因為是先檢測的XML,因此XML排在JSON前面,如果系統兩者的JAR包都存在,那么默認情況下數據會被轉換成XML格式

@RequestMapping(value="/xml", produces={"application/xml; charset=UTF-8"})
@ResponseBody

  使用以上注解,則將會響應轉換為XML 數據格式。

 

我們也可以在項目中使用指定的消息類型轉換器,FastJson 封裝了對應的類型轉換器,只要在項目中引用fastJson對應的依賴配置;

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>     

  通過實現 WebMvcConfigurer 接口來配置指定的消息類型轉換器,

    WebMvcConfigurer接口其實是spring的一種內部配置方式,采用java Bean的形式代替傳統的xml配置形式,可以自定義一些Handler,Interceptor,ViewResolver, MessageConverter。基於java-based方式的spring mvc配置,需要創建一個配置類並實現WebMvcConfigurer 接口;

  springboot2.0版本以后推薦使用這種方式來進行web配置,這樣不會覆蓋掉springboot的一些默認配置。配置類如下:

package com.lf.mp.test;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class CustomHttpMessageConverter implements WebMvcConfigurer {

/**
* 自定義使用FastJsonHttpMessageConverter
*
* @return
*/
@Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteMapNullValue,//保留空的字段
SerializerFeature.WriteNullListAsEmpty,//List null-> []
SerializerFeature.WriteDateUseDateFormat,// 日期格式化
SerializerFeature.WriteNullStringAsEmpty);//String null -> ""

List<MediaType> mediaTypeList = new ArrayList<>();
mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
mediaTypeList.add(MediaType.APPLICATION_JSON);
fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypeList);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
return fastJsonHttpMessageConverter;
}

/**
* 在RsponseBody注解下,Spring處理返回值為String時會用到StringHttpMessageConverter,我們只需要在配置文件中設置好他的編譯編碼就ok了
*
* @return
*/
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
StringHttpMessageConverter httpMessageConverter = new StringHttpMessageConverter();
httpMessageConverter.setDefaultCharset(Charset.defaultCharset());
return httpMessageConverter;
}

//保證StringHttpMessageConverter在FastJsonHttpMessageConverter前被調用
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//converters.removeIf(t -> t instanceof MappingJackson2HttpMessageConverter);
converters.clear();
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
converters.add(converter);
converters.add(fastJsonHttpMessageConverter());
}
}

有兩點需要注意: 

 1.如果沒有配置MediaType.APPLICATION_JSON_UTF8,默認值是MediaType.ALL,FastJsonHttpMessageConverter會去處理消息格式為"text/html;charset=UTF-8"

 2.在RsponseBody注解下,Spring處理返回值為String時會用到StringHttpMessageConverter,我們只需要在配置文件中設置好他的編譯編碼就ok了

如果想了解StringHttpMessageConverter的使用,可以看這篇博客:https://blog.csdn.net/x_iya/article/details/77872173

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM