ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] Date 및 LocalDateTime 을 Json String으로 변환시 주의(Gson 및 Jackson)
    Java/Java Library 2020. 10. 25. 23:45

    Gson 라이브러리 및 Jackson 사용하여 Json String 을 만들때 Date 클래스 및 LocalDateTime 항목이 있는 class 으로 json string 으로 변환하게 되면 변환된 값이 yyyy-MM-dd'T'HH:mm:ss 이러한 포맷으로 변환이 되지 않는다.

     

    이런 경우 모두 커스텀을 해줘야 한다.

     

    Jackson 

    Date with Jackson

    public class ItemDate {
    
      private Integer id; 
      private String name; 
      private String createBy; 
      @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone="Asia/Seoul") 
      private Date createAt; 
        
    }
    

     

    이렇게 하면 "2019-05-15T11:23:10.108+0900" 와 같은 문자열로 변환이된다.

    LocalDateTime with Jackson

    public class ItemLocalDateTime { 
      private Integer id; 
      private String name; 
      private String createBy; 
      JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS") 
      @JsonDeserialize(using = LocalDateTimeDeserializer.class) 
      @JsonSerialize(using = LocalDateTimeSerializer.class) 
      private LocalDateTime createAt; 
    }
    

    이렇게 하면 JSON에서는 "2019-05-15T11:24:46.223" 와 같은 문자열로 변환이된다.

    참고로, TimeZone을 생략했는데, Z를 붙이면 Unsupported field: OffsetSeconds 라는 예외가 발생한다.

    지역 시간은 시간대 필드를 가지고 있지 않기 때문이다. 이것은 ZoneZonedDateTime에 대응하기 때문이다.

     

    Gson

    Gson의 경우 어노테이션이 아니라 GsonBuilder 로 타입을 지정해야한다.

    registerTypeAdapter 을 통해 커스텀이 가능하므로 class 를 따로 만들어준다.

    Date with Gson

    class GsonDateConverter implements JsonSerializer<Date>, JsonDeserializer<Date> { 
    private static final String FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; 
    	@Override 
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { 
        	SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMAT); return src == null ? null : new JsonPrimitive(simpleDateFormat.format(src)); 
      	} 
    
    	@Override 
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
        	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
            try { return json == null ? null : simpleDateFormat.parse(json.getAsString()); } 
            catch (ParseException e) { throw new JsonParseException(e); } 
        } 
    }
    

    LocalDateTime with Gson

    public class GsonLocalDateTimeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
        @Override public JsonElement serialize(LocalDateTime localDateTime, Type srcType, JsonSerializationContext context) {
            return new JsonPrimitive(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime));
        }
    
        @Override public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return LocalDateTime.parse(json.getAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
    }

    사용

    Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new GsonLocalDateTimeAdapter())
    			.registerTypeAdapter(LocalDate.class, new GsonLocalDateAdapter()).create();

    다음처럼  변환하고자 하는 데이터타입 클래스를 어댑터와 같이 registerTypeAdpater 메소드에 추가하면 된다.

     

    반응형

    댓글

Designed by Tistory.