SpringBoot业务开发 04、Springboot统一处理null为空字符串

简介: SpringBoot业务开发 04、Springboot统一处理null为空字符串

一、Jackson方式实现对null字段转为空字符串(springboot自带jackson)


springboot自带jackson,所以不需要额外引入坐标:


编写配置类:我的理解是实例化ObjectMapper对象交由spring管理,之后在使用jackson转化json字符串时执行


@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}




二、fastjson方式实现


需要手动引入依赖fastjson:


<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.35</version>
</dependency>


编写配置类:较完整的配置


该种方式是实现springmvc中的WebMvcConfigurationSupport类重新其中的configureMessageConverters方法,添加一个转换器来对返回值内容进行转换。
@Configuration
public class fastJsonConfig extends WebMvcConfigurationSupport {
    /**
     * 使用阿里 fastjson 作为JSON MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                // 保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的null转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的null转成0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的null转成[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的null转成false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }
}



测试

上面两种方案都可行


我们编写两个类来进行测试:


@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private String address;
}
@RestController
@RequestMapping("/api/v1/test")
@Slf4j  //在类上添加该接口
public class UserController {
    @GetMapping("/{id}")
    public ResultBody test(@PathVariable(value = "id")Integer myid){
        ArrayList<User> users = new ArrayList<>(10);
        users.add(new User((long)111, "changlu", 11, null,null));
        users.add(new User((long)111, null, 11, null,null));
        users.add(new User((long)111, "changlu", 11, null,null));
        users.add(new User((long)111, null, 11, null,null));
        users.add(new User((long)111, "changlu", 11, null,null));
        users.add(new User((long)111, null, 11, null,null));
        users.add(new User((long)111, "changlu", 11, null,null));
        return ResultBody.success(users);
    }
}




转换成功!

相关文章
|
14天前
|
缓存 NoSQL Java
springboot业务开发--springboot集成redis解决缓存雪崩穿透问题
该文介绍了缓存使用中可能出现的三个问题及解决方案:缓存穿透、缓存击穿和缓存雪崩。为防止缓存穿透,可校验请求数据并缓存空值;缓存击穿可采用限流、热点数据预加载或加锁策略;缓存雪崩则需避免同一时间大量缓存失效,可设置随机过期时间。文章还提及了Spring Boot中Redis缓存的配置,包括缓存null值、使用前缀和自定义过期时间,并提供了改造代码以实现缓存到期时间的个性化设置。
|
14天前
|
Java 关系型数据库 MySQL
springboot业务开发--springboot一键生成数据库文档
Screw是一个数据库文档生成工具,能自动化根据数据库表结构生成文档,减轻开发人员工作负担,支持MySQL、MariaDB、TiDB等多种数据库和HTML、Word、Markdown等格式。它依赖HikariCP数据库连接池和Freemarker模板引擎。通过在Spring Boot项目中添加相关依赖并配置,可以用代码或Maven插件方式生成文档。示例代码展示了如何在JUnit测试中使用Screw生成HTML文档。
|
14天前
|
Java 测试技术 Maven
Spring Boot单元测试报错java.lang.IllegalStateException: Could not load TestContextBootstrapper [null]
Spring Boot单元测试报错java.lang.IllegalStateException: Could not load TestContextBootstrapper [null]
|
1月前
|
Java
SpringBoot中静态类使用配置文件经常遇到读取为NULL的情况,现在我就告诉大家。
SpringBoot中静态类使用配置文件经常遇到读取为NULL的情况,现在我就告诉大家。
16 0
|
1月前
|
关系型数据库 MySQL
mysql中判断NULL和空字符串
mysql中判断NULL和空字符串
12 0
|
2月前
|
JSON 前端开发 Java
【SpringBoot实战专题】「开发实战系列」全方位攻克你的技术盲区之Spring定义Jackson转换Null的方法和实现案例
【SpringBoot实战专题】「开发实战系列」全方位攻克你的技术盲区之Spring定义Jackson转换Null的方法和实现案例
46 0
|
2月前
|
Java 数据库连接 mybatis
mybatis plus字段为null或空字符串把原来的数据也更新了,只需要注解
mybatis plus字段为null或空字符串把原来的数据也更新了,只需要注解
24 0
|
2月前
|
移动开发 关系型数据库 MySQL
mysql删除为NULL或者空字符串‘‘或者‘null’的或者删除空格的
mysql删除为NULL或者空字符串‘‘或者‘null’的或者删除空格的
15 1
|
5月前
|
Java 数据库连接 API
SpringBoot【问题 01】借助@PostConstruct解决使用@Component注解的类用@Resource注入Mapper接口为null的问题(原因解析+解决方法)
SpringBoot【问题 01】借助@PostConstruct解决使用@Component注解的类用@Resource注入Mapper接口为null的问题(原因解析+解决方法)
98 0
|
7月前
|
Java 数据库 Spring
spring boot 查询到的数据返回null
spring boot 查询到的数据返回null
253 0