Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Custom JSON Serialization ด้วย Gson ใน Java

Gson Library ให้วิธีระบุ Custom Serializers โดย Register กับ GsonBuilder สร้าง Custom Serializer โดย Override เมธอด serialize() ของคลาส com.google.gson.JsonSerializer

ตัวอย่าง: Custom Serialization สำหรับ Password Field

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<Password> {
    @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) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.address = address;
    }
    
    // Getters, Setters...
    public Password getPassword() { return password; }
    public void setPassword(Password password) { this.password = password; }
}

// Password class
class Password {
    private String password;
    
    public Password(String password) { 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"
}

Use Cases:

  • Encrypt/Encode ค่าระหว่าง Serialize
  • Custom Format (Date, Currency, เป็นต้น)
  • Exclude/Transform Fields เฉพาะบาง Condition
  • Polymorphic Type Handling

คู่คู่: Custom Deserialization ใช้ JsonDeserializer และ deserialize()