HTTP的序列化和反序列化


Netty中的Decoder和Encoder就有兩種基本層次,層次低的一種是Byte <—> Message,二進制與程序內部消息對象之間的轉換,就是常見的序列化/反序列化;另外一種是 Message <—> Message,程序內部對象之間的轉換,比較高層次的序列化/反序列化。

Http協議的處理過程,TCP字節流 <—> HttpRequest/HttpResponse <—> 內部對象,就涉及這兩種序列化。在springmvc中第一步已經由Servlet容器(tomcat等等)幫我們處理了,第二步則主要由框架幫我們處理。上面所說的Http序列化/反序列化就是指的這第二個步驟,它是controller層框架的核心功能之一,有了這個功能,就能大大減少代碼量,讓controller的邏輯更簡潔清晰,就像上面示意的代碼那樣,方法中只有一行代碼。spirngmvc進行第二步操作,也就是Http序列化和反序列化的核心是HttpMessageConverter。

Springboot配置FastJsonHttpMessageConverter有兩種方法:

方法1

啟動類繼承extends WebMvcConfigurerAdapter,然后覆蓋方法configureMessageConverters

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

/** springboot以fastjon方式轉化json數據 */
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
    private static Logger logger = Logger.getLogger(Application.class);

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        //1.需要定義一個convert轉換消息的對象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如:是否要格式化返回的json數據;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

	SerializerFeature[] serializerFeatures = new SerializerFeature[]{
                //    輸出key是包含雙引號
//                SerializerFeature.QuoteFieldNames,
                //    是否輸出為null的字段,若為null 則顯示該字段
//                SerializerFeature.WriteMapNullValue,
                //    數值字段如果為null,則輸出為0
                SerializerFeature.WriteNullNumberAsZero,
                //     List字段如果為null,輸出為[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                //    字符類型字段如果為null,輸出為"",而非null
                SerializerFeature.WriteNullStringAsEmpty,
                //    Boolean字段如果為null,輸出為false,而非null
                SerializerFeature.WriteNullBooleanAsFalse,
                //    Date的日期轉換器
                SerializerFeature.WriteDateUseDateFormat,
                //    循環引用
                SerializerFeature.DisableCircularReferenceDetect,
        };

        fastJsonConfig.setSerializerFeatures(serializerFeatures);
        //3處理中文亂碼問題
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        //5.將convert添加到converters當中.
        converters.add(fastJsonHttpMessageConverter);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
        logger.info("=====spring boot start success====");
    }
}

方法2

添加配置類來注入Bean:HttpMessageConverters

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

import java.nio.charset.Charset;

@Configuration
public class HttpMessageConverterConfig {

    //引入Fastjson解析json,不使用默認的jackson
    //必須在pom.xml引入fastjson的jar包,並且版必須大於1.2.10
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1、定義一個convert轉換消息的對象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //2、添加fastjson的配置信息
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        SerializerFeature[] serializerFeatures = new SerializerFeature[]{
                //    輸出key是包含雙引號
//                SerializerFeature.QuoteFieldNames,
                //    是否輸出為null的字段,若為null 則顯示該字段
//                SerializerFeature.WriteMapNullValue,
                //    數值字段如果為null,則輸出為0
                SerializerFeature.WriteNullNumberAsZero,
                //     List字段如果為null,輸出為[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                //    字符類型字段如果為null,輸出為"",而非null
                SerializerFeature.WriteNullStringAsEmpty,
                //    Boolean字段如果為null,輸出為false,而非null
                SerializerFeature.WriteNullBooleanAsFalse,
                //    Date的日期轉換器
                SerializerFeature.WriteDateUseDateFormat,
                //    循環引用
                SerializerFeature.DisableCircularReferenceDetect,
        };

        fastJsonConfig.setSerializerFeatures(serializerFeatures);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));

        //3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        //4、將convert添加到converters中
        HttpMessageConverter<?> converter = fastConverter;

        return new HttpMessageConverters(converter);
    }
}


免責聲明!

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



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