Spring boot
LocalDateTime, LocalDate Gson 사용해서 전송 시 json형태로 나타날 경우
pakker
2020. 11. 22. 18:28
Date 형태를 LocalDateTime으로 변경 한 후
원래 yyyy-MM-dd HH:mm:ss 로 잘보이던 형태가 json으로 바껴서 나와서 당황
{ "date": { "year": 2020, "month": 11, "day": 22 }, "time": { "hour": 17, "minute": 15, "second": 57, "nano": 0 } }
찾아보니 LocalDateTime과 LocalDate 둘다 해당하는듯
gson사용시에 해결하는 방법이다.
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public 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));
}
}
configure을 하나 만든 후
gson을 선언하는 부분에서
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
이렇게 선언해서 쓰면 된다.
jackson은 어노테이션 쓰면 쉽게 되는거 같은데 gson은 아닌듯..
이거는 Serialize할때 쓰면 되고 Deserialize 일때는 아래 사이트 참고
참고 : www.javaguides.net/2019/11/gson-localdatetime-localdate.html