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

javajsonobject oriented programmingprogramming

JsonConfig  类是一个实用程序类,可帮助配置序列化过程。我们可以使用 JsonConfig  类的 setExcludes() 方法将 bean 转换为具有一些属性的 JSON 对象,这些属性可以排除在外,并将此 JSON 配置实例传递给 JSONObjectstatic  方法的参数。

语法

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

在下面的输出中,可以排除age address 属性。

输出

{
   "firstName": "Raja",
   "lastName": "Ramesh"
}

相关文章