• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot项目中处理返回json的null值(springboot项目为例)

springboot 搞代码 4年前 (2022-01-05) 38次浏览 已收录 0个评论

本文以spring boot项目为例给大家介绍SpringBoot项目中处理返回json的null值问题,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友参考下

在后端数据接口项目开发中,经常遇到返回的数据中有null值,导致前端需要进行判断处理,否则容易出现undefined的情况,如何便捷的将null值转换为空字符串?

以SpringBoot项目为例,SSM同理。

1、新建配置类(JsonConfig.java)

 import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.io.IOException; @Configuration public class JsonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 // Include.Include.ALWAYS 默认 // Include.NON_DEFAULT 属性为默认值不序列化 // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量 // Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化 //objectMapper.setSerializationInclusion(Include.NON_EMPTY); // 字段保留,将null值转为"" objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(""); } }); return objectMapper; } }

2、在启动类Application中,记得添加Scan注解,防止无法扫描到配置类。

ps:下面看下spring boot 使用 json 响应时去除 null 的字段

 import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; public class RespObject implements Serializable { private static final long serialVersionUID = -1560603<strong style="color:transparent">来源gaodai#ma#com搞@@代~&码*网</strong>887556641494L; .... @JsonInclude(Include.NON_NULL) public Object respMsg; @JsonInclude(Include.NON_NULL) public Object respData; .... }

总结

如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

以上就是SpringBoot项目中处理返回json的null值(springboot项目为例)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot项目中处理返回json的null值(springboot项目为例)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址