SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)

目录

  • SpringBoot2.0使用FastJson转换器
    • FastJson 1.2.49
    • SpringBoot 2.0.4.RELEASE
      • 官方文档说明
      • 自定义MVC配置类
      • Content type 'text/plain;charset=UTF-8' not supported

SpringBoot2.0使用FastJson转换器

本篇文章为学习笔记

FastJson 1.2.49

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

SpringBoot 2.0.4.RELEASE

官方文档说明

目前版本依赖MVC的版本为spring-webmvc.5.0.8.RELEASE,Spring官方文档中是这样描述的:
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第1张图片
→文档传送门

自定义MVC配置类

根据文档中的示例,写自己的配置类:
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第2张图片
测试结果成功,FastJson生效。

Content type ‘text/plain;charset=UTF-8’ not supported

项目中增加自定义MVC配置类后,由于指定了MediaType为APPLICATION_JSON_UTF8(application/json;charset=UTF-8)导致一些请求类型不为json格式的接口报错,但是在没有增加自定义WebConfig类之前是不会报错的。
通过DEBUG跟踪至如下类:

org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver

readWithMessageConverters方法中
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第3张图片
表示从转换器中读取给定的类型,如果请求的类型与转换器中类型匹配不到,就会跳出
上图代码块,然后抛出异常。
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第4张图片
在这里插入图片描述
转化器集合中只有FastJson,所以类型不匹配是正常的。
帖两段注释:
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第5张图片
翻译:配置@link HttpMessageConverter,用于读或写请求或响应的主体。如果没有添加转换器,使用注册的转换器的默认列表。注意,在列表中添加了转换器,关闭了默认转换器注册。如果要简单地添加一个转换器而不影响默认注册,考虑使用extendMessageConverters
重新编写WebConfig
将configureMessageConverters方法替换为extendMessageConverters
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第6张图片
发送请求查看this.messageConverters,由于有StringHttpMessageConverter这个转换器,请求类型为text可以通过,但是json类型时fastjson并没有生效。
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第7张图片
方式一:
Debug查看FastJson转换器添加到集合中,但是却没有使用,使用的是MappingJackson这个,所以可以对WebConfig中代码做一个小小修改,将集合中的MappingJackson做替换。
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第8张图片
方式二:
如果请求类型只有json或者text,也可以还是重写configureMessageConverters方法,添加StringHttpMessageConverter
SpringBoot2.0使用FastJson转换器(以及MessageConverter的一些问题)_第9张图片

你可能感兴趣的:(SpringBoot)