json过滤器(处理json值为null,会丢失key的情况)

  • Post author:
  • Post category:其他


private ValueFilter filter = new ValueFilter() {
    @Override
    public Object process(Object obj, String s, Object v) {
        if(v==null)
            return "";
        return v;
    }
};
public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("A","a");
        jsonObject.put("B",null);
        jsonObject.put("C","c");
        System.out.println(jsonObject.toJSONString());
        System.out.println(jsonObject.toJSONString(jsonObject,filter));

        Map map = new HashMap();
        map.put("X","x");
        map.put("Y",null);
        map.put("Z","z");
        System.out.println(jsonObject.toJSONString(map));
        System.out.println(jsonObject.toJSONString(map,filter));
    }
输出:
{"A":"a","C":"c"}
{"A":"a","B":"","C":"c"}
{"X":"x","Z":"z"}
{"X":"x","Y":"","Z":"z"}



版权声明:本文为WSDS_MZM原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。