首頁  >  文章  >  Java  >  在Java中何時使用@JsonAutoDetect註解?

在Java中何時使用@JsonAutoDetect註解?

WBOY
WBOY轉載
2023-09-01 18:01:06794瀏覽

在Java中何時使用@JsonAutoDetect註解?

@JsonAutoDetect 註解可在類別層級使用,以在序列化期間覆寫類別屬性的可見性 反序列化。我們可以使用“creatorVisibility”、“fieldVisibility”、“getterVisibility”、“setterVisibility”等屬性來設定可見性>”和“isGetterVisibility”。JsonAutoDetect類別可以定義類似於Java類別可見性層級的 公共靜態常數,例如“ ANY”、“DEFAULT”、“ NON_PRIVATE”、“NONE”、“PROTECTED_AND_PRIVATE” 和“PUBLIC_ONLY”。

示例

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class JsonAutoDetectTest {
   public static void main(String[] args) throws IOException {
      Address address = new Address("Madhapur", "Hyderabad", "Telangana");
      Name name = new Name("Raja", "Ramesh");
      Student student = new Student(address, name, true);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
      System.out.println("JSON: " + jsonString);
   }
}
// Address class
class Address {
   private String firstLine;
   private String secondLine;
   private String thirdLine;
   public Address(String firstLine, String secondLine, String thirdLine) {
      this.firstLine = firstLine;
      this.secondLine = secondLine;
      this.thirdLine = thirdLine;
   }
   public String getFirstLine() {
      return firstLine;
   }
   public String getSecondLine() {
      return secondLine;
   }
   public String getThirdLine() {
      return thirdLine;
   }
}
// Name class
class Name {
   private String firstName;
   private String secondName;
   public Name(String firstName, String secondName) {
      this.firstName = firstName;
      this.secondName = secondName;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getSecondName() {
      return secondName;
   }
}
// Student class
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
class Student {
   private Address address;
   private Name name;
   private Boolean isActive;
   public Student(Address address, Name name, Boolean isActive) {
      this.address = address;
      this.name = name;
      this.isActive = isActive;
   }
}

輸出

{
 "address" : {
    "firstLine" : "Madhapur",
    "secondLine" : "Hyderabad",
    "thirdLine" : "Telangana"
 },
 "name" : {
    "firstName" : "Raja",
    "secondName" : "Ramesh"
 },
 "isActive" : true
}<strong>
</strong>

以上是在Java中何時使用@JsonAutoDetect註解?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除