在 Java 中使用 Jackson 時,`@JsonUnwrapped` 註釋的重要性是什麼?


@JsonUnwrapped 註釋可以用來在序列化和反序列化過程中解包值。它有助於將組合類的值呈現為它屬於父類。

語法

@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonUnwrapped

示例

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonUnwrappedAnnotationTest {
   public static void main(String args[]) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employee());
      System.out.println(jsonString);
   }
}
class Employee {
   public int empId = 110;
   public String empName = "Raja Ramesh";
   @JsonUnwrapped
   public Address address = new Address();
   // Address class 
   public static class Address {
      public String doorNumber = "1118";
      public String street = "madhapur";
      public String pinCode = "500081";
      public String city = "Hyderabad";
   }
}

輸出

{
   "empId" : 110,
   "empName" : "Raja Ramesh",
   "doorNumber" : "1118",
   "street" : "madhapur",
   "pinCode" : "500081",
   "city" : "Hyderabad"
}

更新於: 09-Jul-2020

609 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.