首頁  >  文章  >  Java  >  如何在Java中使用JsonConfig將bean轉換為JSON物件並排除某些屬性?

如何在Java中使用JsonConfig將bean轉換為JSON物件並排除某些屬性?

王林
王林轉載
2023-09-01 18:37:071436瀏覽

如何在Java中使用JsonConfig將bean轉換為JSON物件並排除某些屬性?

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

#在下面的輸出中,age address 屬性可以被排除。

輸出

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

以上是如何在Java中使用JsonConfig將bean轉換為JSON物件並排除某些屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除