如何使用 flexjson 中的 @JSON 註解透過序列化控制 Java


 @JSON 註解JSONSerializer 類使用,以在序列化過程中排除或包括一個欄位。我們可以使用 JSONSerializer 類的 serialize() 方法對目標例項執行淺序列化。

語法

@Retention(value=RUNTIME)
@Target(value={FIELD,TYPE,METHOD})
public @interface JSON

示例

import flexjson.JSONSerializer;
import flexjson.JSON;
public class JSONAnnotationTest {
   public static void main(String[] args) {
      JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
      Employee emp = new Employee("Raja", "Ramesh", 30, "Hyderabad");
      String jsonStr = serializer.serialize(emp);
      System.out.println(jsonStr);
   }
}
// Employee class
class Employee {
   private String firstName, lastName, address;
   private int age;
   public Employee(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;
   }
   @JSON(include=false)
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   @JSON(include=false)
   public String getAddress() {
      return address;
   }
}

輸出

{
 "age": 30,
 "class": "Employee",
 "firstName": "Raja"
}

更新於: 09-Jul-2020

228 條瀏覽量

開啟你的職業生涯

完成課程,獲得認證

立即開始
廣告