Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 @Expose 주석을 사용하여 JSON에서 필드를 제외하는 방법은 무엇입니까?


Gson @Expose 주석 직렬화 또는 역직렬화에 대해 필드를 노출할지 여부(포함 여부)를 표시하는 데 사용할 수 있습니다. @Expose 주석 두 개의 매개변수를 사용할 수 있으며 각 매개변수는 true 값 중 하나를 취할 수 있는 부울입니다. 또는 거짓 . GSON이 @Expose 주석에 반응하도록 하려면 GsonBuilder 를 사용하여 Gson 인스턴스를 생성해야 합니다. 클래스를 호출하고 excludeFieldsWithoutExposeAnnotation() 메소드에서 Expose 주석이 없는 직렬화 또는 역직렬화의 고려 대상에서 모든 필드를 제외하도록 Gson을 구성합니다.

구문

public GsonBuilder excludeFieldsWithoutExposeAnnotation()

예시

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

출력

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