如何使用 Java 中的 Jackson 在 JSON 中更改一个字段名称?


在 **JSON** 的 **序列化 **或 **反序列化 **过程中,Jackson 注解 @JsonProperty 用于某个属性或方法。它采用一个可选的“name参数 ,当 **JSON** 中的属性名称与“key名称 不同时,此参数很有用。默认情况下,如果键名称与属性名称匹配,则值映射到属性值。

在以下示例中,我们可以在 JSON 中使用 @JsonProperty 注解 更改字段名称

示例

import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonPropertyAnnotationTest {
   public static void main(String[] args) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      User user = new User("Sai", "Adithya", "9959984000", "0402358700");
      String data = mapper.writeValueAsString(user);
      System.out.println(data);
   }
}
// User class
class User {
   @JsonProperty("first-name")
   public String firstName;
   @JsonProperty("last-name")
   public String lastName;
   @JsonProperty("mobile-phone")
   public String mobilePhone;
   @JsonProperty("home_phone")
   public String workPhone;
   public User(String firstName, String lastName, String mobilePhone, String workPhone) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.mobilePhone = mobilePhone;
      this.workPhone = workPhone;
   }
}

输出

{
   "first-name" : "Sai",
   "last-name" : "Adithya",
   "mobile-phone" : "9959984000",
   "home_phone" : "0402358700"
}

更新时间:06-7 月 - 2020

4K+ 浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.