springboot默认使用的是Jackson。接下来讲下如何在springboot项目中使用fastjson。

========以下项目为示例======

说一句废话:这里application用的properties类型的。重点是方法,yml文件中同样适用,不同的只是语言格式而已

①,使用fastjson需要引入依赖


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

十一,SpringBoot-使用FastJson解析Json数据_spring


②,在项目启动类中继承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)

十一,SpringBoot-使用FastJson解析Json数据_mvc_02

③,创建一个实体类PersionModel。

package webdev.model;

import java.util.Date;

public class PersonModel {
private String name;
private String nickName;
private Date birthday;

//geter setter 省略。。。

十一,SpringBoot-使用FastJson解析Json数据_mvc_03

④,Controller中写一个方法调用

@RestController
public class WcbDevController {

@RequestMapping("/getPerInfo")
public Object getPerInfo(){
PersonModel personModel = new PersonModel();
personModel.setBirthday(new Date());
personModel.setNickName("不要喷香水");
return

十一,SpringBoot-使用FastJson解析Json数据_json_04

⑤,启动项目访问

十一,SpringBoot-使用FastJson解析Json数据_json_05

十一,SpringBoot-使用FastJson解析Json数据_json_06

编辑

我们发现日期是毫秒数,姓名出现了乱码。我们知道springboot默认使用的编码是UTF-8,但是这里还是出现了乱码。

解决乱码:在application添加以下配置即可:


spring.http.encoding.force=true

十一,SpringBoot-使用FastJson解析Json数据_json_07


作用是开启springboot对response相应的编码设置。

⑥,重新访问

十一,SpringBoot-使用FastJson解析Json数据_spring_08

十一,SpringBoot-使用FastJson解析Json数据_json_09

编辑

⑦,时间格式

修改时间格式,使用fastjson的注解@JSONField

@JSONField(format = "yyyy-MM-dd")
private

十一,SpringBoot-使用FastJson解析Json数据_spring_10

十一,SpringBoot-使用FastJson解析Json数据_json_11

十一,SpringBoot-使用FastJson解析Json数据_json_12

编辑