搜尋
首頁Javajava教程如何在Java中使用Gson重命名JSON的屬性?

如何在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");
      <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中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境