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"); <strong>Gson </strong>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")<strong> </strong> 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" }
以上是如何在Java中使用Gson重命名JSON的屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!