SpringBoot中使⽤FastjsonJackson对JSON序列化格式化输出
的若⼲问题
来源:
使⽤springboot-web编写rest接⼝,接⼝需要返回json数据,⽬前国内⽐较常⽤的fastjson使⽤⽐较⽅便,但是SpringBoot默认使⽤的Jackson,替换的时候有时候因为其他组件也使⽤到了jackson,所以⽆法100%成功替换。不喜欢使⽤jackson主要是jackson对格式化输出⽀持不太友好,⾃⼰使⽤的时候遇到许多坑,⾄今也没把坑填好,所以⼀直就不待见它,有时候⼜不得不⽤。下⾯总结⼀下
Fastjson/Jackson两种对json序列化+格式化输出的配置总结。
1.Jackson⽅式(SpringBoot中的默认⽅式):
l配置⽂件
spring:
jackson:
#⽇期格式化
date-format: yyyy-MM-dd HH:mm:ss
serialization:
#格式化输出
indent_output: true
⽹上提供的⽅案,可是实际配置并不能⽣效
1.2使⽤JavaConfig⽂件配置Jackson格式化输出
@Configuration
public class JacksonConfig extends WebMvcConfigurationSupport {
/**
* 格式化输出配置
* @param converters
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
jacksonConverter.setPrettyPrint( true ); // 实际使⽤⽣效
}
}
}
}
2.Fastjson⽅式
2.1引⼊fastjson,排除jackson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<!--排除jackson-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--,排除jackson(根据实际情况,下⾯的⾮必须)-->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.4.RELEASE</version>
<!--<exclusions>-->
<!--<exclusion>-->
<!--<groupId>com.</groupId>-->
<!--<artifactId>jackson-databind</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
<scope>compile</scope>
<!--<exclusions>-->
<!--<exclusion>-->
<!--<groupId>com.</groupId>-->
<!--<artifactId>jackson-databind</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
</dependency>
2.2 使⽤JavaConfig配置
SpringBoot中fastjson的配置有两种⽅式:
2.2.1 ⽅式⼀
配置Bean 使⽤fastjson的⽅式实现HttpMessageConverters
@Configuration
public class FastJSONConfig {
/**
* Fastjson
*
* @return
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypes);
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect, //禁⽤循环引⽤
SerializerFeature.PrettyFormat,
SerializerFeature.IgnoreNonFieldGetter
);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter);
}
}
2.2.2⽅式⼆
Spring5.x中实现WebMvcConfigurer接⼝,并重写configureMessageConverters⽅法,向其中添加FastJsonHttpMessageConverter @Configuration
public class FastJsonHttpConverterConfig implements WebMvcConfigurer {
// fastjson配置
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
while(iterator.hasNext()){
HttpMessageConverter<?> converter = ();
if(converter instanceof MappingJackson2HttpMessageConverter){
}
}
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty, // List类型字段为null时输出[]⽽⾮null
SerializerFeature.WriteMapNullValue, // 显⽰空字段
SerializerFeature.WriteNullStringAsEmpty, // 字符串类型字段为null时间输出""⽽⾮null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean类型字段为null时输出false⽽null
SerializerFeature.PrettyFormat, // 美化json输出,否则会作为整⾏输出
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,⽽⾮null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,⽽⾮null
SerializerFeature.WriteDateUseDateFormat, // 时间格式yyyy-MM-dd HH: mm: ss
SerializerFeature.DisableCircularReferenceDetect); // 禁⽤循环引⽤检测
converter.setFastJsonConfig(config);
converters.add(converter);
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
converter.setSupportedMediaTypes(supportedMediaTypes);
}
}
2.2.3 总结
fastjson替换jackson并不能保证100%成功,但是都能最终实现格式化输出。HttpMessageConverter的具体实现需要深⼊阅读源码,从源码上进⼀步寻答案。
使⽤fastjson替换在⾃⼰DIY的OAuth2-SSO项⽬中认证服务器⽆法成功替换,最后基于1中jackson最终实现格式化输出。
3.附Restful接⼝输出json数据
@RestController
public class UserController {
private static final Logger logger = Logger(UserController.class);
/**
* 资源服务器提供的受保护接⼝
* @param authentication
* @return
*/
@GetMapping(value = "/user",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Authentication getUserInfo(Authentication authentication) {
logger.info("authentication resource: user {}", authentication);
System.out.JSONString(authentication, SerializerFeature.PrettyFormat));
return authentication;
}
/**
* 提供⼀个/user/me接⼝供客户端来获得⽤户的凭证
* @param principal
* @return
*/
@GetMapping(value = "/user/me",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Principal getUserPrincipal(Principal principal) {
浏览器json格式化System.out.println("com.acanx.ller.UserController#user Principal:"+principal);
logger.info("Principal: user {}", principal);
System.out.JSONString(principal, SerializerFeature.PrettyFormat));
return principal;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论