Spring Boot之返回JSON数据

来源:互联网 发布:ios移动网络下上传图片 编辑:程序博客网 时间:2024/06/07 00:40

Spring Boot 返回JSON数据

Spring boot默认的解析JSON是jackson,所以实体类返回的时候可以自动解析json格式。

一 自定义json

1引入fastjson的依赖

~xml


com.alibaba
fastjson
1.2.15

~

2.1配置fastjson的方式一

​ a 启动类继承 extends WebMvcConfigurerAdapter

​ b 覆盖方法configureMessageConverters

~~~java
@SpringBootApplication
public class App extends WebMvcConfigurerAdapter{

@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {    super.configureMessageConverters(converters);    /*     * 1、需要先定义一个 convert 转换消息的对象;     * 2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;     * 3、在convert中添加配置信息.     * 4、将convert添加到converters当中.     *      */    // 1、需要先定义一个 convert 转换消息的对象;    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();    //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;    FastJsonConfig fastJsonConfig = new FastJsonConfig();    fastJsonConfig.setSerializerFeatures(            SerializerFeature.PrettyFormat    );    //3、在convert中添加配置信息.    fastConverter.setFastJsonConfig(fastJsonConfig);   // 4、将convert添加到converters当中.    converters.add(fastConverter);}

~~~

2.2配置fastjson方式二

在启动类中注入Bean :HttpMessageConverters

~~~java
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1、需要先定义一个 convert 转换消息的对象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

    //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;    FastJsonConfig fastJsonConfig = new FastJsonConfig();    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);    //3、在convert中添加配置信息.    fastConverter.setFastJsonConfig(fastJsonConfig);    HttpMessageConverter<?> converter = fastConverter;    return new HttpMessageConverters(converter);}

~~~

二 实体类(pojo)格式化

~~~java
public class Demo {
private int id;
private String name;
//com.alibaba.fastjson.annotation.JSONField
@JSONField(format=”yyyy-MM-dd HH:mm”)
private Date createTime;//创建时间.
/*
* 我们不想返回remarks?
* serialize:是否需要序列化属性.
*/
@JSONField(serialize=false)
private String remarks;//备注信息.
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}
~~~

原创粉丝点击