JsonConfig 类是一个帮助配置序列化过程的实用类。我们可以使用JsonConfig 类的setExcludes()方法将一个bean转换为一个JSON对象,并排除其中的一些属性,并将这个JSON配置实例传递给JSONObject的静态方法fromObject()的参数。
public void setExcludes(String[] excludes)
In the below example, we can convert bean to a JSON object by excluding some of the properties.
Example
import net.sf.json.JSONObject; import net.sf.json.JsonConfig; public class BeanToJsonExcludeTest { public static void main(String[] args) { Student student = new Student("Raja", "Ramesh", 35, "Madhapur"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(new String[]{"age", "address"}); JSONObject obj = JSONObject.fromObject(student, jsonConfig); System.out.println(obj.toString(3)); //pretty print JSON } public static class Student { private String firstName, lastName, address; private int age; public Student(String firstName, String lastName, int age, String address) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; this.address = address; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public String getAddress() { return address; } } }
输出
{ "firstName": "Raja", "lastName": "Ramesh" }
以上就是如何在Java中使用JsonConfig将bean转换为JSON对象并排除某些属性?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。