๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“ฑ| Android/โœ… | ์—๋Ÿฌํ•ด๊ฒฐ

[Android, Kotlin] Retrofit์—์„œ LocalDateTime ๋ฐ์ดํ„ฐ ๋ฐ›์•„์˜ค๊ธฐ

by immgga 2023. 11. 6.

1. ์˜ค๋ฅ˜ ์ƒํ™ฉ

retrofit์—์„œ localDateTime ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์˜ค๋˜ ์ค‘ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค.

์˜ค๋ฅ˜ ๋‚ด์šฉ

์œ„์˜ ์˜ค๋ฅ˜๋Š” LocalDateTime parsing์—์„œ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ฒจ์„œ ๋ฐœ์ƒํ•˜๋Š” ์˜ค๋ฅ˜์ด๋‹ค.

์ด ์˜ค๋ฅ˜๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด์„œ ํ•„์ž๋Š” ๊ฒ€์ƒ‰์„ ๊ธฐ๋ฐ˜์œผ๋กœ gson์— ๊ธฐ์กด์˜ localDatetime์„ parsing ํ•˜๋Š” ์ž‘์—…์˜ ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜์˜€๋‹ค.

val gson = GsonBuilder()
    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    .create()

return GsonConverterFactory.create(gson)

์œ„์˜ ๋ฐฉ๋ฒ•์€ ๋‚˜์—๊ฒŒ ์˜ฌ๋ฐ”๋ฅธ ๋ฐฉ๋ฒ•์ด ์•„๋‹ˆ์—ˆ๋‹ค.

 

๊ทธ๋Ÿฌ๋‚˜ ๋‚˜๋Š” ํ•œ ๋ธ”๋กœ๊ทธ์—์„œ ๋ฐฉ๋ฒ•์„ ์ฐพ์„ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

https://lemontia.tistory.com/997

 

[retrofit, gson] Expected BEGIN_OBJECT but was STRING ์—๋Ÿฌ ํ•ด๊ฒฐ(String -> LocalDate)

Retrofit์„ ์‚ฌ์šฉํ•˜๋ฉด์„œ ์œ„์˜ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋Š”๋ฐ, ํ™•์ธํ•ด๋ณด๋‹ˆ String ์„ ํŠน์ • ํƒ€์ž…์œผ๋กœ ๋ณ€๊ฒฝํ• ๋•Œ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ๋‹ค. ์ •ํ™•ํžˆ๋Š” Retrofit์ด ์•„๋‹Œ Gson ์—์„œ ๋ณ€ํ™˜ํ•˜๋˜ ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ ๊ฒƒ์ด๋‹ค. ์ƒ˜ํ”Œ์„ ํ†ตํ•ด ์•Œ

lemontia.tistory.com

์ด ๋ธ”๋กœ๊ทธ์—์„œ๋Š” ์„œ๋ฒ„์˜ ๋ฐ์ดํ„ฐ๋ฅผ String์„ ์ด์šฉํ•ด ๋ฐ›์•„์˜ค๋Š” ๋ฐฉ๋ฒ•๊ณผ

LocalDateTime์˜ Type์„ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐฉ๋ฒ• ๋ชจ๋‘๋ฅผ ์•Œ๋ ค์ฃผ์—ˆ๋‹ค.

์ผ๋‹จ ๋‚˜๋Š” ์ „์ž์˜ ๋ฐฉ๋ฒ•์„ ํƒํ•ด์„œ ์ด ์˜ค๋ฅ˜๋ฅผ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

data class RentalInfoResponse(
    val rentalStartDate: String,
    val rentalEndDate: String
)

๊ธฐ์กด์— LocalDateTime์œผ๋กœ ์„ค์ •๋˜์–ด ์žˆ๋˜ ๋ถ€๋ถ„์„ String์œผ๋กœ ๋ฐ”๊พธ์–ด์„œ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

LocalDateTime์˜ ๋ฐ์ดํ„ฐ ํ˜•์‹์„ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์˜ค๊ณ  ์‹ถ์œผ๋ฉด ์œ„์˜ ๋งํฌ๋ฅผ ๋“ค์–ด๊ฐ€์„œ ์ ์šฉํ•ด ๋ณด๋Š” ๊ฒƒ๋„ ๋‚˜์˜์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™๋‹ค.

728x90