Spring Boot 完美支持阿里里巴巴 FastJSON:
- 第一种实现方式
- Application 继承 WebMvcConfigurerAdapter;
- 重写 configureMessageConverters 方法;
- 完整代码示例:
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
public class DemoApplication extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
// 1. 定义一个 converter 转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
// 2. 添加 FastJSON 的配置信息,比如是否要格式化返回的 JSON 数据;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3. 在 converter 中添加配置配置信息;
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
// 4. 将 converter 添加到 converters 当中;
converters.add(fastJsonHttpMessageConverter);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 第二种实现方式
- 直接使用
@Bean
注入第三方 JSON 解析框架:
- 完整代码:
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.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
@SpringBootApplication
public class DemoApplication {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1. 定义一个 converter 转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
// 2. 添加 FastJSON 的配置信息,比如是否要格式化返回的 JSON 数据;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3. 在 converter 中添加配置配置信息;
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
-
@com.alibaba.fastjson.annotation.JSONField
注解
// 格式化返回的数据
@JSONField(format = "yy/MM/dd HH:mm")
private Date createDate;
// 是否序列化,默认为 true,则可以返回到前端
@JSONField(serialize = false)
private String remarks;