gson이 LocalDate와 LocalDateTime을 알아듣지 못하여 config를 통과하며 400 에러를 냈다.
gson이 LocalDate와 LocalDateTime을 알아들을 수 있도록 직렬화와 역직렬화를 구현했다.
gson에 아래 구현할 녀석들 알려주기
private Gson gson;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());
gson = gsonBuilder.setPrettyPrinting().create();
class LocalDateSerializer implements JsonSerializer <LocalDate> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Override
public JsonElement serialize(LocalDate localDate, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(localDate));
}
}
class LocalDateDeserializer implements JsonDeserializer <LocalDate> {
@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDate.parse(json.getAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd").withLocale(Locale.KOREA));
}
}
class LocalDateTimeSerializer implements JsonSerializer <LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public JsonElement serialize(LocalDateTime localDateTime, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(localDateTime));
}
}
class LocalDateTimeDeserializer implements JsonDeserializer <LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDateTime.parse(json.getAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withLocale(Locale.KOREA));
}
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Seoul")
private final LocalDateTime localDateTime;
final LocalDateTime dateTime = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
감사합니다 선생님...java.lang.reflect.InaccessibleObjectException으로 떠서 이것저것 해봤는데 이 문제였네요