Gson 라이브러리는 GsonBuilder 에 사용자 정의 역직렬 변환기를 등록하여 사용자 정의 역직렬 변환기를 지정하는 방법을 제공합니다. java 객체를 JSON으로 변환하는 방법이 필요한 경우 . deserialize()를 재정의하여 맞춤 역직렬 변환기를 만들 수 있습니다. com.google.gson.JsonDeserialize 메소드 r 수업.
아래 예에서 사용자 정의 역직렬화 구현 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 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; } }
출력
admin@123