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

Làm cách nào để loại trừ một trường khỏi JSON bằng cách sử dụng chú thích @Expose trong Java?


Gson @Expose chú thích có thể được sử dụng để đánh dấu một trường được hiển thị hoặc không (bao gồm hoặc không) để tuần tự hóa hoặc giải mã hóa. Chú thích @Expose có thể nhận hai tham số và mỗi tham số là một boolean có thể nhận giá trị true hoặc sai . Để GSON phản ứng với các chú thích @Expose, chúng tôi phải tạo một phiên bản Gson bằng cách sử dụng GsonBuilder và cần phải gọi ExclusiveFieldsWithoutExposeAnnotation () , nó định cấu hình Gson để loại trừ tất cả các trường được xem xét để tuần tự hóa hoặc giải mã hóa không có chú thích Expose.

Cú pháp

public GsonBuilder excludeFieldsWithoutExposeAnnotation()

Ví dụ

import com.google.gson.*;
import com.google.gson.annotations.*;
public class JsonExcludeAnnotationTest {
   public static void main(String args[]) {
      Employee emp = new Employee("Raja", 28, 40000.00);
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
      gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
      jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
   }
}
// Employee class
class Employee {
   @Expose(serialize = true, deserialize = true)
   public String name;
   @Expose(serialize = true, deserialize = true)
   public int age;
   @Expose(serialize = false, deserialize = false)
   public double salary;
   public Employee(String name, int age, double salary) {
      this.name = name;
      this.age = age;
      this.salary = salary;
   }
}

Đầu ra

{
 "name": "Raja",
 "age": 28,
 "salary": 40000.0
}
{
 "name": "Raja",
 "age": 28
}