Thư viện Gson cung cấp cách chỉ định custom deserializer bằng cách đăng ký custom deserializer với GsonBuilder khi cần chuyển đối tượng Java sang JSON. Tạo custom deserializer bằng cách override phương thức deserialize() của lớp com.google.gson.JsonDeserializer.
Ví dụ minh họa
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 {
@Override
public Password deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String ecryptedPwd = json.getAsString();
return new Password(new StringBuffer(ecryptedPwd).toString());
}
}
// Lớp Student
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;
}
// getters/setters...
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 + " ]";
}
}
// Lớp Password
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; }
}
Kết quả đầu ra
admin@123
Giải thích: Ví dụ này demo custom deserializer cho field password (kiểu Password object thay vì String). JSON chứa string "admin@123", deserializer chuyển thành Password object. Đăng ký qua GsonBuilder.registerTypeAdapter(Password.class, new PasswordDeserializer()).