用jsonObject轉換json字符時過濾bean中空值節點

例:Test test = new Test();
    test.setId("1");
    test.setName("zhangsan");
    jsonObject.fromobject(test,Test.class).toString;
輸出:{"id":"1","name":"zhangsan"}

假如不封裝name屬性,只封裝id屬性
    Test test = new Test();
    test.setId("1");
    jsonObject.fromobject(test,Test.class).toString;
輸出:{"id":"1","name":""}
如果只輸出:{"id":"1"}
這樣的json字符,有什麼方法可以解決麼?


************************************************************

4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
    Test t = new Test();
    t.id = 10;
         
    JsonConfig jsonConfig = new JsonConfig();
    PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
            return null == fieldValue;
            }
    };
    jsonConfig.setJsonPropertyFilter(filter);
    System.out.println(JSONObject.fromObject(t, jsonConfig).toString());
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章