信息发布→ 登录 注册 退出

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

发布时间:2026-01-11

点击量:
目录
  • JSONObject.toJSONString 过滤值为空的key
    • 情况
    • 也就是这个方法
  •  JSONObject.toJSONString自动过滤空值

    JSONObject.toJSONString 过滤值为空的key

    情况

    public static String getJsonResult(int status, String msg, Object data){undefined
            Map<String, Object> resultMap=new HashMap<String, Object>();        
            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<String, Object> resultMap=new HashMap<String, Object>();
            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);

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

    在线客服
    服务热线

    服务热线

    4008888355

    微信咨询
    二维码
    返回顶部
    ×二维码

    截屏,微信识别二维码

    打开微信

    微信号已复制,请打开微信添加咨询详情!