바보같은 gson에게 LocalDate나 LocalDateTime 알려주기

leverest96·2022년 12월 11일
0

Trouble Shooting

목록 보기
5/20
post-thumbnail

문제 상황

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();
  • LocalDate Serializer & Deserializer
    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));
        }
    }
  • LocalDateTime Serializer & Deserializer
    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));
        }
    }
    • LocalDateTime의 경우 Field명에 JsonFormat을 정의해줘야 gson에서도 알아먹는다.
      @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Seoul")
      private final LocalDateTime localDateTime;
    • 위의 코드로 Test Code 작성 중 현재 시간을 받아올 때 second 단위 아래로 인해서 오류가 발생하는데 아래의 코드로 second 단위 아래를 제거할 수 있다.
      final LocalDateTime dateTime = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
profile
응애 난 애기 개발자

0개의 댓글