Demo实体类:
package com.xf.hello; /** * 测试实体 */ public class Demo { private int id; private String name; 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; } }
controller:
//spring boot默认使用json解析框架是jackson @RequestMapping("/getDemo") public Demo getDemo(){ Demo demo=new Demo(); demo.setId(1); demo.setName("张三"); return demo; }
测试:
fastjson:
第一种:
pom.xml
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
实体:
HelloApplication
package com.xf.hello; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; @SpringBootApplication //指定这是一个spring boot应用程序 public class HelloApplication extends WebMvcConfigurerAdapter { @Override public 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); } public static void main(String[] args) { SpringApplication.run(HelloApplication.class, args); } }
//spring boot默认使用json解析框架是jackson @RequestMapping("/getDemo") public Demo getDemo(){ Demo demo=new Demo(); demo.setId(1); demo.setName("张三"); demo.setCreateTime(new Date()); return demo; }
第二种:
/** * 在这里我们使用 @Bean注入 fastJsonHttpMessageConvert * @return */ @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); }
补充:
直接在这设置
/* * 我们不想返回remarks? * serialize:是否需要序列化属性. */ @JSONField(serialize=false) private String remarks;//备注信息.