1. 第一种方式,实现JSONString接口的方法
public class Person implements JSONString { private String name; private String age; private Address address; // getters & setters public String toJSONString() { return "{name:‘"+name+"‘,age:‘"+age+"‘}"; }}
public class Test { public static void main(String[] args) { Person person = new Person("xxb", "27"); System.out.println(JSONObject.fromObject(person).toString()); } }
2.第二种方式,通过jsonconfig实例,对包含和需要排除的属性进行方便的添加或删除(建立JsonConfig实例,并配置属性排除列表)
public class Person { private String name; private String age; private Address address; // getters & setters }
public class Test { public static void main(String[] args) { Person person = new Person("xxb", "27"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExclusions( new String[]{"address"}); System.out.println(JSONObject.fromObject(person,jsonConfig).toString()); } }
时间: 2024-10-10 04:47:55