好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

JSONObject.toJSONString 过滤值为空的key

情况

?

1

2

3

4

5

6

7

8

9

10

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序列化属性

也就是这个方法

?

1

JSONObject.toJSONString(Object object, SerializerFeature... features)  

?

1

2

3

4

5

6

7

    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);

    }

?

1

2

3

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避免这种情况

?

1

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

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

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

查看更多关于使用JSONObject.toJSONString 过滤掉值为空的key的详细内容...

  阅读:62次