1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
解释:
springboot
默认使用Jackson-databind
作为JSON
处理器,使用fastjson
就需要先剔除jackson-databind
2.fastjson自定义配置(有两种方式)
方式一:
@Configuration
public class MyFastJsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
//输出类名
SerializerFeature.WriteClassName,
//输出map中value为null的数据
SerializerFeature.WriteMapNullValue,
//json格式化
SerializerFeature.PrettyFormat,
//输出空list为[],而不是null
SerializerFeature.WriteNullListAsEmpty,
//输出空string为"",而不是null
SerializerFeature.WriteNullStringAsEmpty
);
converter.setFastJsonConfig(config);
return converter;
}
}
方式二:
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
//输出类名
SerializerFeature.WriteClassName,
//输出map中value为null的数据
SerializerFeature.WriteMapNullValue,
//json格式化
SerializerFeature.PrettyFormat,
//输出空list为[],而不是null
SerializerFeature.WriteNullListAsEmpty,
//输出空string为"",而不是null
SerializerFeature.WriteNullStringAsEmpty
);
converter.setFastJsonConfig(config);
converters.add(converter);
}
}
3.application.properties额外配置
#设置响应编码
spring.http.encoding.force-response=true
4.测试
- 先定义一个model
@Getter
@Setter
@AllArgsConstructor
public class Book {
private String name;
private String author;
protected float price;
private Date date;
}
- 定义路由
@RestController
public class BookController {
@GetMapping("/book")
public Book book(){
return new Book("小罗","小三",30f,new Date());
}
}
- 接口调用
使用浏览器访问http://localhost:8080/book,页面展示如下:
{ "@type":"com.xzl.spire.model.Book", "author":"小三", "date":"2020-11-08", "name":"小罗", "price":30.0F }
5.Gson配置
Gson配置请看文章:springboot配置Gson
网友评论