SpringBoot入门笔记使用fastjson

Posted ZGJ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot入门笔记使用fastjson相关的知识,希望对你有一定的参考价值。

1、添加fastjson配置

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

2、重写configureMessageConverters

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
FastJsonConfig    fastJsonConfig=new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}

3、运行http://127.0.0.1:8080/getstudent

浏览器输出有乱码
4、修改Controller

@RequestMapping(value = "/getstudent", produces = "application/json; charset=utf-8")
    public Student getStudent() {
        Student student=new Student();
        student.id=1;
        student.name="小明";
        return student;
    }

5、再次运行,正常,并且可以看到fastjson已经自动格式化了输出内容

6、常用注解
@JSONField(serialize = false)  //不参与格式化

@JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue) //输出NULL

7、也可以代码中直接使用
System.out.println(JSON.toJSONStringWithDateFormat(ao, "yyyy-MM-dd HH:mm:ss.SSS")); 

总结:本篇其实和SpringBoot关系不大,传统SpringMVC+Hibernate也可以用。

以上是关于SpringBoot入门笔记使用fastjson的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot使用fastjson

FastJson处理数据出现错误 com.alibaba.fastjson.JSONException: syntax error, expect {, actual error, pos 1(示例代

springboot使用FastJson返回Json视图

springboot使用阿里fastjson来解析数据

SpringBoot入门学习笔记

springBoot系列教程05:fastjson的集成配置及使用