学无先后,达者为师

网站首页 前端文档 正文

使用JSONObject.toJSONString 过滤掉值为空的key_java

作者:起名-困难户   更新时间: 2022-05-03 前端文档

JSONObject.toJSONString 过滤值为空的key

情况

public static String getJsonResult(int status, String msg, Object data){undefined
        Map resultMap=new HashMap();        
        resultMap.put("status", status);
        resultMap.put("msg", msg);
        resultMap.put("data", data);
        return JSONObject.toJSONString(resultMap);
    }
public static void main(String[] args) {undefined
        System.out.println(getJsonResult(1, "success", null));
    }

结果

{"msg":"success","status":1}

从输出结果可以看出,null对应的key已经被过滤掉;这明显不是我们想要的结果,这时我们就需要用到fastjson的SerializerFeature序列化属性

也就是这个方法

JSONObject.toJSONString(Object object, SerializerFeature... features)  
    public static String getJsonResult(int status, String msg, Object data){undefined
        Map resultMap=new HashMap();
        resultMap.put("status", status);
        resultMap.put("msg", msg);
        resultMap.put("data", data);
        return JSONObject.toJSONString(resultMap,SerializerFeature.WriteMapNullValue);
    }
public static void main(String[] args) {undefined
        System.out.println(getJsonResult(1, "success", null));
    }

结果

{"msg":"success","data":null,"status":1}

 JSONObject.toJSONString自动过滤空值

使用fastjson将javabean转string时,默认会将值为null的属性过滤掉,

可通过设置SerializerFeature.WriteMapNullValue避免这种情况

String value = JSONObject.toJSONString(objectData, SerializerFeature.WriteMapNullValue);

原文链接:https://blog.csdn.net/liu123342/article/details/82379738

栏目分类
最近更新