Gson लाइब्रेरी GsonBuilder के साथ एक कस्टम डी-सीरियलाइज़र रजिस्टर करके कस्टम डी-सीरियलाइज़र्स को निर्दिष्ट करने का एक तरीका प्रदान करती है यदि हमें Java ऑब्जेक्ट को JSON में बदलने का एक तरीका चाहिए। हम com.google.gson.JsonDeserializer क्लास के deserialize() मेथड को ओवरराइड करके एक कस्टम डी-सीरियलाइज़र बना सकते हैं।
नीचे दिए गए उदाहरण में, JSON के कस्टम डी-सीरियलाइज़ेशन का इम्प्लीमेंटेशन।
उदाहरण
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());
}
}
// 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;
}
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 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; }
}
आउटपुट
admin@123