springboot 中使用fastjson

  • fastjson 是什么

FastJSON是一个Java语言编写的高性能,功能完善,完全支持http://json.org的标准的JSON库。简而言之就是一个数据的转换工具。

  • 为什么要使用fastjson 

数据转换工具这么多,springboot本身就自带了jackson,那么为啥要用fastjson 呢,从其名字上我们能找出答案,那就是一个字,快。

  • springboot中怎么使用fastjson

说了这么多,那么我们怎么在项目中使用这个工具呢。

首先,在项目依赖中加入依赖包

 <dependency>
2     <groupId>com.alibaba</groupId>
3     <artifactId>fastjson</artifactId>
4     <version>1.1.23</version>
5 </dependency>

其次,配置fastjson

方式:在启动类中,注入Bean:HttpMessageConverters ,蓝色部分为转换器定义部分

package com.bfhl;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.EnableTransactionManagement;


import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.bfhl.utils.JsonUtils;
import com.bfhl.web.session.EnableRedisHttpSession;
@SpringBootApplication
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=1800*16)//8小时
@EnableScheduling
@EnableAsync
@EnableTransactionManagement//开启数据库事务
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class WebApp extends SpringBootServletInitializer{

public static void main(String[] args) {
    SpringApplication.run(WebApp.class, args);
}

    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder application) {
        return application.sources(WebApp.class);
    }
    
    /**
     * @return 替换掉默认的json,使用FastJson
     */
   // @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();


        //3处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFeatures(JsonUtils.features);;
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        return new HttpMessageConverters(converter);


    }

@Bean
public Executor mySimpleAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(5);
executor.initialize();
return executor;
}
}
最后,就可以使用配置好的fastjson 工具了,


private int id;

private String name;

//添加一个当前时间字段

@JSONField(format = "yyyy-MM-dd HH:mm")

private Date createTime;


这样我们页面获取到的结果和不加转换的对比如下:


  • 最后再介绍一下HttpMessageConverter的是怎样工作的,以下部分来自 网页转发

大部分人的第一反应是通过SpringMVC拦截器(Interceptor)中的postHandler方法处理。实际这是行不通的,因为当程序运行到该方法,是在返回数据之后,渲染页面之前,所以这时候HttpServletResponse中的输出流已经关闭了,自然无法在对返回数据进行处理。

其实这个问题用几行代码就可以搞定,因为SpringMVC提供了非常丰富的扩展支持,无论是之前提到的MethodArgumentResolverHandlerMethodReturnValueHandler,还是接下来要提到的HttpMessageConverter

在SpringMVC的 Controller层经常会用到@RequestBody@ResponseBody,通过这两个注解,可以在Controller中直接使用Java对象作为请求参数和返回内容,而完成这之间转换作用的便是HttpMessageConverter

HttpMessageConverter

1 方法介绍


HttpMessageConverter接口提供了5个方法:

  • canRead:判断该转换器是否能将请求内容转换成Java对象
  • canWrite:判断该转换器是否可以将Java对象转换成返回内容
  • getSupportedMediaTypes:获得该转换器支持的MediaType类型
  • read:读取请求内容并转换成Java对象
  • write:将Java对象转换后写入返回内容

其中readwrite方法的参数分别有有HttpInputMessageHttpOutputMessage对象,这两个对象分别代表着一次Http通讯中的请求和响应部分,可以通过getBody方法获得对应的输入流和输出流。

2 继承体系


当前SpringMVC中已经默认提供了相当多的转换器,如上图,其中常用的有:

作用 读支持MediaType 写支持MediaType
ByteArrayHttpMessageConverter 数据与字节数组的相互转换 */* application/octet-stream
StringHttpMessageConverter 数据与String类型的相互转换 text/* text/plain
FormHttpMessageConverter 表单与MultiValueMap的相互转换 application/x-www-form-urlencoded application/x-www-form-urlencoded
SourceHttpMessageConverter 数据与javax.xml.transform.Source的相互转换 text/xml和application/xml text/xml和application/xml
MarshallingHttpMessageConverter 使用Spring的Marshaller/Unmarshaller转换XML数据 text/xml和application/xml text/xml和application/xml
MappingJackson2HttpMessageConverter 使用Jackson的ObjectMapper转换Json数据 application/json application/json
MappingJackson2XmlHttpMessageConverter 使用Jackson的XmlMapper转换XML数据 application/xml application/xml
BufferedImageHttpMessageConverter 数据与java.awt.image.BufferedImage的相互转换 Java I/O API支持的所有类型 Java I/O API支持的所有类型

3 如何工

当用户发送请求后,@RequestBody注解会读取请求body中的数据,通过获取请求头Header中的Content-Type来确认请求头的数据格式,从而来为请求数据适配合适的转换器。例如contentType:applicatin/json,那么转换器会适配MappingJackson2HttpMessageConverter。响应时候的时候同理,@ResponseBody注解会通过检测请求头Header中Accept属性来适配对应响应的转换器。


总结:

该问主要介绍了一个数据转换的工具,并演示了怎么在springboot 中使用的过程,以及介绍了httpmessageConverter转换器的工作过程。




猜你喜欢

转载自blog.csdn.net/jtcode_is_my_partner/article/details/81005482