去掉JSON中值为null的

在作接口开发经常会用到JSON数据格式,可是在有些时间类型属性为null时转换会报错,解决方法我这里是把为null的去掉。json

//正经常使用jsonObject序列化后获得字符串  
//{id:18, name:"张山"}  
// 如今若是name=null的话 我不想让它系列化 我想返回这样的结果{id:18},

异常以下:app

处理方法:ide

很简单net.sf.json在格式化中能够传递一个JsonConfig,实现setJsonPropertyFilter方法而后修改apply方法便可。code

JsonConfig config = new JsonConfig();  
config.setJsonPropertyFilter(new PropertyFilter()  {  
    @Override  
    public boolean apply(Object source, String name, Object value){  
        return value.equals("null");  
    }  
});  
JSONArray jsonArray = JSONArray.fromObject(object, config);  
System.out.println(jsonArray);

JDK1.8中有更风骚的写法:接口

JsonConfig config = new JsonConfig();  
config.setJsonPropertyFilter((source, name, value) -> value.equals("null"));
JSONArray jsonArray = JSONArray.fromObject(object, config);  
System.out.println(jsonArray);
相关文章
相关标签/搜索