首頁 > Java > java教程 > @JsonIdentityInfo註解在Java中使用Jackson的重要性是什麼?

@JsonIdentityInfo註解在Java中使用Jackson的重要性是什麼?

WBOY
發布: 2023-09-23 09:37:02
轉載
1344 人瀏覽過

@JsonIdentityInfo註解在Java中使用Jackson的重要性是什麼?

當物件在 Jackson 函式庫中具有父子關係時,將使用@JsonIdentityInfo註解。 @JsonIdentityInfo 註解 用於在序列化和反序列化過程中指示物件身分。 ObjectIdGenerators.PropertyGenerator 是一個抽象佔位符類,用來表示要使用的物件識別碼來自 POJO 屬性的情況。

語法

@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonIdentityInfo
登入後複製

範例

import java.util.*;
import java.io.*;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonIdentityInfoTest {
   public static void main(String[] args) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      User user = new User(115, "Raja", "Ramesh");
      Address address = new Address(125, "Madhapur", "Hyderabad", user);
      user.addAddress(address);
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(address);
      System.out.println(jsonString);
   }
}
// User class
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "userId")
class User {
   private int userId;
   private String firstName;
   private String lastName;
   private List<Address> addresses;
   public User(int userId, String firstName, String lastName) {
      this.userId = userId;
      this.firstName = firstName;
      this.lastName = lastName;
      this.addresses = new ArrayList<Address>();
   }
   public int getUserId() {
      return userId;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void addAddress(Address address) {
      addresses.add(address);
   }
}
// Address class
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "userId")<strong>
</strong>class Address {
   private int userId;
   private String city;
   private String street;
   private User user;
   public Address(int userId, String street, String city, User user) {
      this.userId = userId;
      this.street = street;
      this.city = city;
      this.user = user;
   }
   public int getUserId() {
      return userId;
   }
   public String getStreet() {
      return street;
   }
   public String getCity() {
      return city;
   }
   public User getUser() {
      return user;
   }
}
登入後複製

輸出

{
 "userId" : 125,
 "city" : "Hyderabad",
 "street" : "Madhapur",
 "user" : {
    "userId" : 115,
    "firstName" : "Raja",
    "lastName" : "Ramesh"
    }
}
登入後複製

以上是@JsonIdentityInfo註解在Java中使用Jackson的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板