Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để kiểm soát tuần tự hóa thông qua chú thích @JSON bằng cách sử dụng flexjson trong Java?


Chú thích @JSON được sử dụng bởi JSONSerializer lớp để loại trừ hoặc bao gồm một trường trong quá trình tuần tự hóa. Chúng tôi có thể sử dụng serialize () phương pháp của JSONSerializer lớp để thực hiện tuần tự hóa nông của cá thể đích.

Cú pháp

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

Ví dụ

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

Đầu ra

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