如何通过在Java中使用JsonConfig排除某些属性来将bean转换为JSON对象?

JsonConfig 类是一个工具类,它可帮助您配置序列化过程。我们可以使用JsonConfig 类的setExcludes()方法将具有很少属性的Bean转换为JSON对象,并将此JSON配置实例传递给JSONObject静态 方法f romObject() 的参数。

语法

public void setExcludes(String[] excludes)

在下面的示例中,我们可以通过排除一些属性将bean转换为JSON对象。

示例

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"
}