Spring boot FastJson
Posted Chris,Cai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot FastJson相关的知识,希望对你有一定的参考价值。
介绍:FastJson 是ailibaba 的一款解析Json的开源框架
使用方式1
引入jar 包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
@SpringBootApplication
//启动类extends WebMvcConfigurerAdapter public class App extends WebMvcConfigurerAdapter{
//重写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); } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
使用方式2
@SpringBootApplication public class App { //使用@Bean 依赖注入 @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
FastJson 其他用法:
格式化:
@JSONField(format = "yyyy-MM-dd")
private Date createDate;
自定义名称:
@JSONField(name = "AGE")
private int age;
将 Java 对象转换换为 JSON 对象:
JSON.toJSONString()
创建JSON 对象:
public void whenGenerateJson_thanGenerationCorrect() throws ParseException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < 2; i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("AGE", 10); jsonObject.put("FULL NAME", "Doe " + i); jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonArray.add(jsonObject); } String jsonOutput = jsonArray.toJSONString(); }
JSON 对象需要转java对象:
public void whenJson_thanConvertToObjectCorrect() { Person person = new Person(20, "John", "Doe", new Date()); String jsonObject = JSON.toJSONString(person); Person newPerson = JSON.parseObject(jsonObject, Person.class) }
以上是关于Spring boot FastJson的主要内容,如果未能解决你的问题,请参考以下文章
FastJson/spring boot: json输出方法二