一,使用Spring Boot默认Json解析框架jackson
1,创建一个实体类Persion
package com.zh.json; public class Persion { private int pid;
private String pname;
private int age;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Persion(int pid, String pname, int age) {
super();
this.pid = pid;
this.pname = pname;
this.age = age;
}
public Persion() {
super();
}
}
2,创建一个方法getPersion返回一个Persion对象
3,访问
二,使用Spring Boot使用fastjon解析Json
1,在pom.xml添加fastjon的先关依赖
<!-- 添加fastjson 依赖包. -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
2,Spring Boot支持2种配置方式使用fastjon解析Json
1)第一种方法就是:
(1)启动类继承extends WebMvcConfigurerAdapter
(2)覆盖方法configureMessageConverters
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters); // 1、需要先定义一个 converter 转换消息的对象;
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);
}
(3)在Persion类中添加一个Date属性,使用fastjon格式化时间
@JSONField(format="yyyy-MM-dd HH:mm")
private Date date; public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
(4)启动类中创建一个getDatePersion方法,并访问
@RequestMapping("/getDatePersion")
public Persion getDatePersion(){
Persion p = new Persion(1, "张三", 20);
p.setDate(new Date());
return p;
}
2)第二种方法就是:
(1)在App.java启动类中,注入Bean : HttpMessageConverters
@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);
}
(2)启动类中创建一个getDatePersion2方法,并访问