springboot配置Jackson返回统⼀默认值的实现⽰例在项⽬开发中,我们返回的数据或者对象没有的时候⼀般直接返回的null
有数据时的返回值
{
"flag": true,
"code": "10000",
"msg": "成功!",
"data": {
"id": 32,
"templateType": 1,
"templateName": "我的测试模板1",
"freightName": "我的测试标题1",
"listArea": [
{
"id": 968,
"templateId": 32,
"freightPrice": 15,
}
],
"templateDescEntity": {
"id": 1
"name": "xxx"
}
}
}
没有数据时的返回值
{
"flag": true,
"code": "10000",
"msg": "成功!",
"data": {
"id": 32,
"templateType": 1,
"templateName": null,
"freightName": null,
"listArea": null,
"templateDescEntity": null
}
}
这种情况下数据返回给前端,前端需要做⼤量的空值判断
如前端调使⽤属性plateDescEntity.id的时候就会直接报异常
此时我们可以使⽤返回值统⼀处理,配置如下
<dependency>
<groupId>com.</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
java类添加配置
package com.fig;
import com.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.dition.ConditionalOnMissingBean;
import t.annotation.Bean;
import t.annotation.Configuration;
import t.annotation.Primary;
import org.verter.json.Jackson2ObjectMapperBuilder;
import java.io.IOException;
import flect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 数据返回给前端时,设置null值默认为""
*
* @author cgh
* @date 2020/12/14 10:35
*/
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = ateXmlMapper(false).build();
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
String fieldName = OutputContext().getCurrentName();
try {
//反射获取字段类型
Field field = CurrentValue().getClass().getDeclaredField(fieldName);
if (CharSequence.class.Type())) {
//字符串型空值""
jsonGenerator.writeString("");
return;
} else if (Collection.class.Type())) {
//列表型空值返回[]
jsonGenerator.writeStartArray();
jsonGenerator.writeEndArray();
return;
} else if (Map.class.Type())) {
//map型空值或者 bean对象返回{}
jsonGenerator.writeStartObject();
jsonGenerator.writeEndObject();
return;
}
} catch (NoSuchFieldException ignored) {
}
jsonGenerator.writeString("");
}
});
return objectMapper;
}
}
添加空值统⼀处理后的返回值
{
"flag": true,
"code": "10000",
"msg": "成功!",
"data": {
"id": 32,
"templateType": 1,
"templateName": "",
"freightName": "",
"listArea": [],
"templateDescEntity": {}
}
write的返回值
}
到此这篇关于springboot配置Jackson返回统⼀默认值的实现⽰例的⽂章就介绍到这了,更多相关springboot Jackson返回统⼀默认值内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。