如何用 Java 中的 Gson 實現自定義 JSON 序列化?


如果我們需要一種將 **java 物件轉換為 JSON** 的方法,那麼 Gson 庫提供了一種方法,即透過向 **GsonBuilder** 註冊自定義序列化程式來指定自定義序列化程式。我們可以重寫 com.google.gson.JsonSerializer 類**的 serialize()** 方法來建立自定義序列化程式。

在下面的示例中,實現了 JSON 的 **自定義序列化**。

示例

import java.lang.reflect.Type;
import com.google.gson.*;
public class CustomJSONSerializerTest {
   public static void main(String[] args) {
      Gson gson = new GsonBuilder().registerTypeAdapter(Password.class, new PasswordSerializer())
.setPrettyPrinting().create();
      Student student = new Student("Adithya", "Jai", 25, "Chennai");
      student.setPassword(new Password("admin@123"));
      System.out.println(gson.toJson(student));
   }
}
class PasswordSerializer implements JsonSerializer {
   @Override
   public JsonElement serialize(Password src, Type typeOfSrc, JsonSerializationContext context) {
      return new JsonPrimitive(new StringBuffer(src.getPassword()).toString());
   }
}
// Student class
class Student {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   private Password password;
   public Student(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 void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public Password getPassword() {
      return password;
   }
   public void setPassword(Password password) {
      this.password = password;
   }
   public String toString() {
      return "Student[ " +
               "firstName = " + firstName +
               ", lastName = " + lastName +
               ", age = " + age +
               ", address = " + address +
             " ]";
   }
}
// Password class
class Password {
   private String password;
   public Password(String password) {
      super();
      this.password = password;
   }
   public String getPassword() {
      return password;
   }
   public void setPassword(String password) {
      this.password = password;
   }
}

輸出

{
  "firstName": "Adithya",
  "lastName": "Jai",
  "age": 25,
 "address": "Chennai",
 "password": "admin@123"
}

更新於:2020 年 7 月 4 日

1K+ 瀏覽量

開啟你的 職業

完成課程後獲得認證

開始
廣告