springboot返回给前端数据将null值转化为空字符串

迈不过友情╰ 2022-12-15 12:39 465阅读 0赞

springboot返回给页面的json数据中,如果有数据为null,则返回空字符串。

springboot默认使用jackson解析返回json数据。

我们做一下配置:

  1. package com.yhcode.config;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.databind.JsonSerializer;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.fasterxml.jackson.databind.SerializerProvider;
  6. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.context.annotation.Primary;
  10. import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
  11. import java.io.IOException;
  12. /** * 处理 jackson 返回的null值 * */
  13. @Configuration
  14. public class JacksonConfig {
  15. @Bean
  16. @Primary
  17. @ConditionalOnMissingBean(ObjectMapper.class)
  18. public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
  19. ObjectMapper objectMapper = builder.createXmlMapper(false).build();
  20. objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
  21. @Override
  22. public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
  23. jsonGenerator.writeString("");
  24. }
  25. });
  26. return objectMapper;
  27. }
  28. }

这样就可以将返回json中的null值转为空字符串了。

转载自:https://blog.csdn.net/MisshqZzz/article/details/84977616?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

发表评论

表情:
评论列表 (有 0 条评论,465人围观)

还没有评论,来说两句吧...

相关阅读