ไลบรารี Gson ให้วิธีระบุ Custom Deserializers โดย Register กับ GsonBuilder สร้าง Custom Deserializer โดย Override เมธอด deserialize() ของคลาส com.google.gson.JsonDeserializer
ตัวอย่าง: Custom Deserialization สำหรับ Password Field
import java.lang.reflect.Type;
import com.google.gson.*;
public class CustomJSONDeSerializerTest {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Password.class, new PasswordDeserializer())
.setPrettyPrinting()
.create();
String jsonStr = "{" +
"\"firstName\": \"Adithya\"," +
"\"lastName\": \"Sai\"," +
"\"age\": 25," +
"\"address\": \"Pune\"," +
"\"password\": \"admin@123\"" +
"}";
Student student = gson.fromJson(jsonStr, Student.class);
System.out.println(student.getPassword().getPassword());
}
}
class PasswordDeserializer implements JsonDeserializer<Password> {
@Override
public Password deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String encryptedPwd = json.getAsString();
return new Password(new StringBuffer(encryptedPwd).toString());
}
}
// Student class
class Student {
private String firstName;
private String lastName;
private int age;
private String address;
private Password password;
// Constructors, 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; }
}
ผลลัพธ์
admin@123
Use Cases:
- Decrypt/Decode ค่าระหว่าง Deserialize
- Map JSON Structure ที่ต่างจาก Java Class
- Custom Date/Time Parsing
- Handle Polymorphic Types
คู่คู่: Custom Serialization ใช้ JsonSerializer และ serialize() method