SpringBoot默认json解析器详解和字段序列化⾃定义
前⾔
在我们开发项⽬API接⼝的时候,⼀些没有数据的字段会默认返回NULL,数字类型也会是NULL,这个时候前端希望字符串能够统⼀返回空字符,数字默认返回0,那我们就需要⾃定义json序列化处理
SpringBoot默认的json解析⽅案
我们知道在springboot中有默认的json解析器,Spring Boot 中默认使⽤的 Json 解析技术框架是 jackson。我们点开 l 中的spring-boot-starter-web 依赖,可以看到⼀个 spring-boot-starter-json依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.4.7</version>
<scope>compile</scope>
</dependency>
Spring Boot 中对依赖都做了很好的封装,可以看到很多 spring-boot-starter-xxx 系列的依赖,这是 Spring Boot 的特点之⼀,不需要⼈为去引⼊很多相关的依赖了,starter-xxx 系列直接都包含了所必要的依赖,所以我们再次点进去上⾯这个 spring-boot-starter-json 依赖,可以看到:
<dependency>
<groupId>com.</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.dule</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.11.4</version>
<scope>compile</scope>
</dependency>
我们在controller中返回json时候通过注解@ResponseBody就可以⾃动帮我们将服务端返回的对象序列化成json字符串,在传递json body 参数时候 通过在对象参数上@RequestBody注解就可以⾃动帮我们将前端传过来的json字符串反序列化成java对象
这些功能都是通过HttpMessageConverter这个消息转换⼯具类来实现的
SpringMVC⾃动配置了Jackson和Gson的HttpMessageConverter,SpringBoot对此做了⾃动化配置
JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
@Configuration(proxyBeanMethods =false)
@ConditionalOnClass(ObjectMapper.class)
@ConditionalOnBean(ObjectMapper.class)
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue ="jackson", matchIfMissing =true)
static class MappingJackson2HttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class,
ignoredType ={
"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",
"org.st.webmvc.alps.AlpsJsonHttpMessageConverter"})
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper){ return new MappingJackson2HttpMessageConverter(objectMapper);
}
}
JacksonAutoConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
@Configuration(proxyBeanMethods =false)
@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
static class JacksonObjectMapperConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
ateXmlMapper(false).build();
}
}
Gson的⾃动化配置类
org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration
@Configuration(proxyBeanMethods =false)
@ConditionalOnBean(Gson.class)
@Conditional(PreferGsonOrJacksonAndJsonbUnavailableCondition.class)
static class GsonHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean
GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson){
GsonHttpMessageConverter converter =new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
}
⾃定义SprinBoot的JSON解析
⽇期格式解析
默认返回的是时间戳类型格式,但是时间戳会少⼀天需要在数据库连接url上加上时区如:
spring.datasource.url=jdbc:p6spy:mysql://47.100.78.146:3306/mall?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8& serverTimezone=GMT%2B8&autoReconnect=true
1. 使⽤@JsonFormat注解⾃定义格式
@JsonFormat(pattern ="yyyy-MM-dd")
private Date birthday;
但是这种要对每个实体类中的⽇期字段都需要添加此注解不够灵活
2. 全局添加
在配置⽂件中直接添加spring.jackson.date-format=yyyy-MM-dd
NULL字段不返回
1. 在接⼝中如果不需要返回null字段可以使⽤@JsonInclude注解
@JsonInclude(JsonInclude.Include.NON_NULL)
private String title;
但是这种要对每个实体类中的字段都需要添加此注解不够灵活
2. 全局添加 在配置⽂件中直接添加spring.jackson.default-property-inclusion=non_null
⾃定义字段序列化
⾃定义null字符串类型字段返回空字符NullStringJsonSerializer序列化
public class NullStringJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)throws IOException {
if(o ==null){
jsonGenerator.writeString("");
springboot框架的作用}
}
}
⾃定义null数字类型字段返回0默认值NullIntegerJsonSerializer序列化
public class NullIntegerJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)throws IOException {
if(o ==null){
jsonGenerator.writeNumber(0);
}
}
}
⾃定义浮点⼩数类型4舍5⼊保留2位⼩数DoubleJsonSerialize序列化
public class DoubleJsonSerialize extends JsonSerializer {
private DecimalFormat df =new DecimalFormat("##.00");
@Override
public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)throws IOException { if(value !=null){
jsonGenerator.String(),2));
}else{
jsonGenerator.writeString("0.00");
}
}
}
⾃定义NullArrayJsonSerializer序列化
public class NullArrayJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)throws IOException { if(o==null){
jsonGenerator.writeStartArray();
}else{
jsonGenerator.writeObject(o);
}
}
}
⾃定义BeanSerializerModifier使⽤我们⾃⼰的序列化器进⾏bean序列化
public class MyBeanSerializerModifier extends BeanSerializerModifier {
private JsonSerializer _nullArrayJsonSerializer =new NullArrayJsonSerializer();
private JsonSerializer _nullStringJsonSerializer =new NullStringJsonSerializer();
private JsonSerializer _nullIntegerJsonSerializer =new NullIntegerJsonSerializer();
private JsonSerializer _doubleJsonSerializer =new DoubleJsonSerialize();
@Override
public List changeProperties(SerializationConfig config, BeanDescription beanDesc,
List beanProperties){// 循环所有的beanPropertyWriter
for(int i =0; i < beanProperties.size(); i++){
BeanPropertyWriter writer =(BeanPropertyWriter) (i);
// 判断字段的类型,如果是array,list,set则注册nullSerializer
if(isArrayType(writer)){//给writer注册⼀个⾃⼰的nullSerializer
writer.assignNullSerializer(this.defaultNullArrayJsonSerializer());
}
if(isStringType(writer)){
writer.assignNullSerializer(this.defaultNullStringJsonSerializer());
}
if(isIntegerType(writer)){
writer.assignNullSerializer(this.defaultNullIntegerJsonSerializer());
}
if(isDoubleType(writer)){
writer.assignSerializer(this.defaultDoubleJsonSerializer());
}
}
return beanProperties;
}// 判断是什么类型
protected boolean isArrayType(BeanPropertyWriter writer){
Class clazz = PropertyType();
return clazz.isArray()|| clazz.equals(List.class)|| clazz.equals(Set.class);
}
protected boolean isStringType(BeanPropertyWriter writer){
Class clazz = PropertyType();
return clazz.equals(String.class);
}
protected boolean isIntegerType(BeanPropertyWriter writer){
Class clazz = PropertyType();
return clazz.equals(Integer.class)|| clazz.equals(int.class)|| clazz.equals(Long.class);
}
protected boolean isDoubleType(BeanPropertyWriter writer){
Class clazz = PropertyType();
return clazz.equals(Double.class)|| clazz.equals(BigDecimal.class);
}
protected JsonSerializer defaultNullArrayJsonSerializer(){
return _nullArrayJsonSerializer;
}
protected JsonSerializer defaultNullStringJsonSerializer(){
return _nullStringJsonSerializer;
}
protected JsonSerializer defaultNullIntegerJsonSerializer(){
return _nullIntegerJsonSerializer;
}
protected JsonSerializer defaultDoubleJsonSerializer(){
return _doubleJsonSerializer;
}
}
应⽤我们⾃⼰bean序列化使其⽣效 提供MappingJackson2HttpMessageConverter类
在配置类中提供MappingJackson2HttpMessageConverter类,使⽤ObjectMapper 做全局的序列化
@Configuration
public class ClassJsonConfiguration {
@Bean
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter(){
final MappingJackson2HttpMessageConverter converter =new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = ObjectMapper();
// 为mapper注册⼀个带有SerializerModifier的Factory,此modifier主要做的事情为:判断序列化类型,根据类型指定为null时的值 mapper.SerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
return converter;
}
}
此类会代替SpringBoot默认的json解析⽅案。事实上,此类中起作⽤的是ObjectMapper 类,因此也可直接配置此类。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论