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

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) {
        SpringApplication.run(WebDevApplication.class,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 personModel;
    }

}

⑤,启动项目访问

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

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

spring.http.encoding.force=true

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

⑥,重新访问

 

⑦,时间格式

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

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

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不要喷香水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值