如何使用 Java 中的 Gson 重新命名 JSON 屬性?


Gson @SerializedName 註解可以序列化為 JSON,其欄位名稱為提供的名稱值。此註解可以覆蓋任何FieldNamingPolicy,包括可能已設定在Gson例項上的預設欄位命名策略。可以使用 GsonBuilder 類設定其他命名策略。

語法

@Retention(value=RUNTIME)
@Target(value={FIELD,METHOD})
public @interface SerializedName

示例

import com.google.gson.annotations.*;
import com.google.gson.*;
public class SerializedNameAnnotationTest {
   public static void main(String args[]) {
      Employee emp = new Employee("Rahul", "Dev", 30, "Nagpur");
      Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
      String jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
   }
}
// Employee class
class Employee {
   @SerializedName("first_name")
   private String firstName;
   @SerializedName("last_name")
   private String lastName;
   private int age;
   private String address;
   public Employee() {
   }
   public Employee(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   public String getAddress() {
      return address;
   }
}

輸出

{
 "first_name": "Rahul",
 "last_name": "Dev",
 "age": 30,
 "address": "Nagpur"
}

更新時間:06-Jul-2020

3K+ 瀏覽量

開啟您的 職業

完成課程獲得認證

開始瞭解
廣告
© . All rights reserved.