在 Java 中,使用 Jackson 的 @JsonRootName 註解有何重要性?


@JsonRootName 註解可用於封裝一個物件,以頂級元素的形式進行序列化。我們可將名稱作為引數傳遞給 @JsonRootName 註解。我們可使用 SerializationFeature enum 的 "WRAP_ROOT_VALUE" 特性,可啟用它,讓根值封裝在一個單個屬性 JSON 物件中,其中鍵是根名稱。

示例

import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonRootNameAnnotationTest {
   public static void main(String args[]) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(new Employee());
      System.out.println(jsonString);
   }
}

@JsonRootName(value = "user")
class Employee {
   public int empId = 125;
   public String empName = "Raja Ramesh";
}

輸出

{"user":{"empId":125,"empName":"Raja Ramesh"}}

更新於:2020 年 7 月 8 日

1K+ 次瀏覽

開始你的 事業

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.