I have a problem with deserialisation. I have this json from server
{
"rooms": [
{
"id": 1,
"name": "Стандартный номер с видом на бассейн",
"price": 186600,
"price_per": "За 7 ночей с перелетом",
"peculiarities": [
"Включен только завтрак",
"Кондиционер"
],
"image_urls": [
"https://www.atorus.ru/sites/default/files/upload/image/News/56871/%D1%80%D0%B8%D0%BA%D1%81%D0%BE%D1%81%20%D1%81%D0%B8%D0%B3%D0%B5%D0%B9%D1%82.jpg",
"https://q.bstatic.com/xdata/images/hotel/max1024x768/267647265.jpg?k=c8233ff42c39f9bac99e703900a866dfbad8bcdd6740ba4e594659564e67f191&o=",
"https://worlds-trip.ru/wp-content/uploads/2022/10/white-hills-resort-5.jpeg"
]
},
{
"id": 2,
"name": "Люкс номер с видом на море",
"price": 289400,
"price_per": "За 7 ночей с перелетом",
"peculiarities": [
"Все включено",
"Кондиционер",
"Собственный бассейн"
],
"image_urls": [
"https://mmf5angy.twic.pics/ahstatic/www.ahstatic.com/photos/b1j0_roskdc_00_p_1024x768.jpg?ritok=65&twic=v1/cover=800x600",
"https://www.google.com/search?q=%D0%BD%D0%BE%D0%BC%D0%B5%D1%80+%D0%BB%D1%8E%D0%BA%D1%81+%D0%B2+%D0%BE%D1%82%D0%B5%D0%BB%D0%B8+%D0%B5%D0%B3%D0%B8%D0%BF%D1%82%D0%B0+%D1%81+%D1%81%D0%BE%D0%B1%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D1%8B%D0%BC+%D0%B1%D0%B0%D1%81%D1%81%D0%B5%D0%B9%D0%BD%D0%BE%D0%BC&tbm=isch&ved=2ahUKEwilufKp-4KBAxUfJxAIHR4uAToQ2-cCegQIABAA&oq=%D0%BD%D0%BE%D0%BC%D0%B5%D1%80+%D0%BB%D1%8E%D0%BA%D1%81+%D0%B2+%D0%BE%D1%82%D0%B5%D0%BB%D0%B8+%D0%B5%D0%B3%D0%B8%D0%BF%D1%82%D0%B0+%D1%81+%D1%81%D0%BE%D0%B1%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D1%8B%D0%BC+%D0%B1%D0%B0%D1%81%D1%81%D0%B5%D0%B9%D0%BD%D0%BE%D0%BC&gs_lcp=CgNpbWcQAzoECCMQJ1CqAVi6HGDmHWgAcAB4AIABXIgB3wySAQIyNZgBAKABAaoBC2d3cy13aXotaW1nwAEB&sclient=img&ei=Y3fuZOX7KJ_OwPAPntyE0AM&bih=815&biw=1440#imgrc=Nr2wzh3vuY4jEM&imgdii=zTCXWbFgrQ5HBM",
"https://tour-find.ru/thumb/2/bsb2EIEFA8nm22MvHqMLlw/r/d/screenshot_3_94.png"
]
}
]
}
and I want to get a List
HotelApi.kt
@GET("f9a38183-6f95-43aa-853a-9c83cbb05ecd")
suspend fun getRooms(): Response<List<Room>>
for this i wrote a JsonDeserializer<List>
RoomListDeserializer.kt
class RoomListDeserializer : JsonDeserializer<List<Room>> {
override fun deserialize(
json: JsonElement,
typeOfT: Type?,
context: JsonDeserializationContext?
): List<Room> {
val roomList = mutableListOf<Room>()
val roomsJsonArray = json.asJsonObject.getAsJsonArray("rooms")
Log.d("TAG", "deserialize: ${roomsJsonArray}")
roomsJsonArray?.forEach { roomJson ->
val room = context?.deserialize<Room>(roomJson, Room::class.java)
room?.let { roomList.add(it) }
}
return roomList
}
}
(log doesn't call out) and i added it to GsonBuilder
AppModule.kt
@Provides
@Singleton
fun provideGsonConverter(): Gson = GsonBuilder()
.registerTypeAdapter(object : TypeToken<List<Room>>(){}.type, RoomListDeserializer())
.create()
@Provides
@Singleton
fun provideHotelApi(
client: OkHttpClient,
gson: Gson
): HotelsApi = Retrofit.Builder()
.baseUrl(HotelsApi.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(HotelsApi::class.java)
and it doesnt work
HotelRepositoryImpl.kt
override suspend fun getRooms(): Flow<Resource<List<Room>>> = flow {
try {
val response = api.getRooms()
if (response.body() != null) {
emit(Resource.Success(response.body()!!))
} else {
emit(Resource.Error(context.getString(R.string.response_is_null)))
}
} catch (e: Exception) {
Log.d("TAG", "getRooms: $e")
emit(handleException(e, context))
}
}.flowOn(Dispatchers.IO)
Expeption is
getRooms: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
But if I create a class with a field with a Room list, everything works fine
data class Test(
val rooms: List<Room>
)
My Room entity
data class Room(
val id: Int,
@SerializedName("image_urls")
val imageUrls: List<String>,
val name: String,
val peculiarities: List<String>,
val price: Int,
@SerializedName("price_per")
val pricePer: String
)
Can i achive my goal, and how?
The type you provide for GsonBuilder.registerTypeAdapter
is checked exactly. Though the documentation might not make this clear enough. When you register an adapter for List<Room>
, then you only register it for that exact type. It will neither be used for ArrayList<Room>
nor for List<? extends Room>
or similar.
This appears to be part of the reason why your code is not working. It seems the Kotlin expression object : TypeToken<List<Room>>(){}.type
actually creates a List<? extends Room>
(can be seen when debugging)[1]. So your custom deserializer will not be called.
Maybe you can work around this by replacing object : TypeToken<List<Room>>(){}.type
with TypeToken.getParameterized(List::class.java, Room::class.java).type
, but that seems rather brittle.
Another alternative would be to implement your custom deserialization logic using a TypeAdapterFactory
instead, but then you would have to check there manually if the type is List<Room>
or a subtype.
So maybe the easiest and most reliable solution would be really to have some enclosing type which has a rooms
property, like you did it with your Test
data class.
[1] I don't know though why Kotlin is apparently not treating the List<Room>
in the return type of getRooms()
as List<? extends Room>
as well.