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

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

PHPz
PHPz앞으로
2023-09-16 21:49:02561검색

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

Gson @Expose 주석은 직렬화 또는 역직렬화를 위해 필드가 노출되는지(포함 여부)를 표시하는 데 사용할 수 있습니다. @Expose 주석 은 두 개의 매개변수를 사용할 수 있으며, 각 매개변수는 true 또는 false 값을 사용할 수 있는 부울 값입니다. 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)<strong>
</strong>   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
}

위 내용은 Java에서 @Expose 주석을 사용하여 JSON에서 필드를 제외하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제