使用默认
我们知道,要整合web项目,就要添加web依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在这个依赖中默认加入了jackson-databind作为JSON处理器,所以导入了web的依赖就不需要再添加额外的JSON处理器就能放回一个JSON数据了;
@RequestMapping("test")
@ResponseBody
//放回json数据
public student getString(){
return new student("小明",20);
}
页面显示
这是通过Spring中默认的提供的MappingJackson2HttpMassageConverter来实现的,当然开发者也可以通过自定义json转换器;
自定义类型转换器:
常见的JSON处理器除了jackson-databind之外,还有Gson和fastjson这里针对常见的用法分别举例:
使用Gson
Gson时Google的一个开源的JSON解析框架,使用Gson,需要先除去默认的jackson-databind,然后加入Gson依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
由于Spring Boot中默认提供了Gson的自动类型转换类GsonHttpMessageConverterConfiguration,因此Gson的依赖添加成功后可以象jackson-databing那样直接使用Gson。但想对日期数据进行格式化还需要自定义HttpMessageConverter;
GsonHttpMessageConverterConfiguration的一段源码如下:
@Bean
@ConditionalOnMissingBean
GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
@ConditionalOnMissingBean注解表示当项目中没有提供GsonHttpMessageConverter时才会使用默认的GsonHttpMessageConverter,所以我们只需要提供一个GsonHttpMessageConverter就可以了:
@Configuration
public class GsonConfig {
@Bean
GsonHttpMessageConverter gsonHttpMessageConverter(){
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyyy/MM/dd");//设置日期格式
builder.excludeFieldsWithModifiers(Modifier.PROTECTED);//将修饰符为protected的字段过滤掉
Gson gson = builder.create();
converter.setGson(gson);
return converter;
}
}