Map获取String判断空值问题

今天在写一个开源项目的时候遇到一个问题,为了图省事我直接在接口上用Map接受前端发送过来的数据,之后再一一解析,其中有一些参数我需要判断是否为空或0(为空就是前端传递undefined情况),最开始的想法是做containskey判断,但是要判断的数据还不少,为了偷懒而且写那么多if代码也不好看,所以我就用LamdaQueryWrapper在获取值的时候判断条件是否成立,下面是我的写法

String brandId = String.valueOf(params.get("brandId"));
String status = String.valueOf(params.get("status"));
String catelogId = String.valueOf(params.get("catelogId"));
wrapper.eq(!StringUtils.isEmpty(status),
                        SpuInfoEntity::getPublishStatus, params.get("status"))
                .eq(brandId != null && !"0".equals(brandId), SpuInfoEntity::getBrandId,
                        params.get("brandId"))
                .eq(catelogId != null && !"0".equals(catelogId), SpuInfoEntity::getCatalogId,
                        params.get("catelogId"));

一开始我觉得我的代码逻辑上没有问题,但是一启动项目做测试就发现问题了,模糊查询(前端传递undefined)的情况下查不出来数据,我看了日志打印的sql,查询的时候加上了对catalog_id等数据的条件判断,我以为是我逻辑上出现了问题,但是一复盘确实不应该出现这样的结果,所以我想应该是条件判断语句出现了问题,于是我做了测试

        System.out.println(params.get("catelogId"));
        System.out.println(params.get("catelogId") != null);
        System.out.println(String.valueOf(params.get("catelogId")));
        System.out.println(String.valueOf(params.get("catelogId")) != null);
        System.out.println((String) params.get("catelogId"));
        System.out.println((String) params.get("catelogId") != null);
        System.out.println(catelogId != null);
        System.out.println(!"0".equals(catelogId));
        System.out.println(catelogId != null && !"0".equals(catelogId));

上述语句输出结果如下

null
false
null
true
null
false
true
true
true

问题就出现在String.valueOf上,点击去其实就能看到这里是做了空值判断,如果为空就赋值“null”,所以 String.valueOf(params.get("catelogId")) 不是null对象而是“null”字符串对象,正常强转成String对象的就不存在这个问题

 

posted @ 2022-07-28 20:29  Cra2iTeT  阅读(372)  评论(0编辑  收藏  举报