쉽게 개체를 복사 할 수 있도록 내 개체에 날짜 값을 long
으로 저장합니다. 또한 개체를 serialize 할 때 날짜 필드 만 재정의하고 프로세스의 모든 필드를 쓸 필요가없는 방법을 원했습니다. 이것이 내가 생각해 낸 해결책이다. 이것을 처리하는 최적의 방법인지는 확실치 않지만 잘 수행하는 것 같습니다.
클래스는 여기 Date
을 String
으로 구문 분석하는 데 사용되는 사용자 정의 클래스입니다.
public final class Person {
private final String firstName;
private final String lastName;
private final long birthDate;
private Person(String firstName, String lastName, Date birthDate) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate.getTime();
}
public static Person getInstance(String firstName, String lastName, Date birthDate) {
return new Person(firstName, lastName, birthDate);
}
public String toJson() {
return new GsonBuilder().registerTypeAdapter(Person.class, new PersonSerializer()).create().toJson(this);
}
public static class PersonSerializer implements JsonSerializer<Person> {
@Override
public JsonElement serialize(Person person, Type type, JsonSerializationContext context) {
JsonElement personJson = new Gson().toJsonTree(person);
personJson.getAsJsonObject().add("birthDate", new JsonPrimitive(DateUtil.getFormattedDate(new Date(policy.birthDate), DateFormat.USA_DATE)));
return personJson;
}
}
}
클래스가 직렬화
는
birthDate
필드는 포맷
String
대신
long
값으로 반환됩니다.
위의 문제는 위임을위한'new Gson()'입니다. 기존의 gson (이 유형 어댑터와 별개로 자체 커스터마이징이 가능할 수도 있음)을 사용할 수 있다면 완벽한 솔루션이 될 것입니다. 어떤 아이디어? – Mar0ux
@ Mar0ux, 나는 당신의 요지를 보았습니다. 'Gson' 객체가 클래스의 정적 멤버가 아니라면 어떻게 작동하는지 실제로 알 수 없습니다. 나는 Gson을 더 이상 사용하지 않는다. Spring과의 통합이 잘되어 있기 때문에 Jackson으로 전환했습니다. – Jason