Kotlin & Java
[Retrofit2] GSON Converter 사용시 LocalDateTime..
y0ngha
2021. 11. 24. 19:18
Gson을 이용해 JSON으로 직렬화 시킨 후 데이터를 보내야 하는 문제가 있었다.
LocalDateTime을 직렬화 하니 아래와 같은 문자열이 나와서 당황했다..
{ "date": { "year": 2021, "month": 11, "day": 24 }, "time": { "hour": 19, "minute": 15, "second": 57, "nano": 0 } }
찾아보니 Gson은 따로 직렬화 클래스를 만들어서 넣어주면 된다고 한다.
1
2
3
4
5
6
|
class LocalDateTimeSerializer : JsonSerializer<LocalDateTime> {
private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
override fun serialize(src: LocalDateTime?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
return JsonPrimitive(formatter.format(src))
}
}
|
cs |
위와 같이 Serializer 클래스를 하나 만들어주고.. Retrofit Gson Converter 넣는 곳에 아래와 같이 작성해주자.
1
|
private val gson: Gson = GsonBuilder().registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeSerializer()).setPrettyPrinting().setLenient().create()
|
cs |
이제 저 Gson을 ConverterFactory에 넣어주면 된다.
출처)