十一,SpringBoot-使用FastJson解析Json数据
原创
©著作权归作者所有:来自51CTO博客作者不要喷香水的原创作品,请联系作者获取转载授权,否则将追究法律责任
springboot默认使用的是Jackson。接下来讲下如何在springboot项目中使用fastjson。
========以下项目为示例======
说一句废话:这里application用的properties类型的。重点是方法,yml文件中同样适用,不同的只是语言格式而已
①,使用fastjson需要引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
②,在项目启动类中继承WebMvcConfigurerAdapter,并重写configureMessageConverters
public class WebDevApplication extends WebMvcConfigurerAdapter {
//重写fastJson消息转换器
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//创建fastJson消息转换器
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//创建配置对象
FastJsonConfig config = new FastJsonConfig();
//对json数据进行格式化
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
converter.setFastJsonConfig(config);
converters.add(converter);
}
public static void main(String[] args)

③,创建一个实体类PersionModel。
package webdev.model;
import java.util.Date;
public class PersonModel {
private String name;
private String nickName;
private Date birthday;
//geter setter 省略。。。

④,Controller中写一个方法调用
@RestController
public class WcbDevController {
@RequestMapping("/getPerInfo")
public Object getPerInfo(){
PersonModel personModel = new PersonModel();
personModel.setBirthday(new Date());
personModel.setNickName("不要喷香水");
return

⑤,启动项目访问


编辑
我们发现日期是毫秒数,姓名出现了乱码。我们知道springboot默认使用的编码是UTF-8,但是这里还是出现了乱码。
解决乱码:在application添加以下配置即可:
spring.http.encoding.force=true
作用是开启springboot对response相应的编码设置。
⑥,重新访问


编辑
⑦,时间格式
修改时间格式,使用fastjson的注解@JSONField
@JSONField(format = "yyyy-MM-dd")
private



编辑