例: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字符,有什么方法可以解决么?

解决方案 »

  1.   

    重载fromobject,或者把Test再封装成map
      

  2.   

    Json lib 2.3版本
    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());
    }
    输出为: {"id":10}