Guilherme Delgado
01/31/2022, 5:47 PMMap<String, String>
json response from github’s API into a List<Object>
but I’m failing to do so, more in the threadGuilherme Delgado
01/31/2022, 5:48 PM@Serializable
data class Emoji(val name: String, val imageUrl: String)
Guilherme Delgado
01/31/2022, 5:48 PM@OptIn(ExperimentalSerializationApi::class, InternalSerializationApi::class)
object EmojiListSerializer : KSerializer<List<Emoji>> {
override val descriptor: SerialDescriptor = mapSerialDescriptor<String, String>()
override fun deserialize(decoder: Decoder): List<Emoji> {
val list = mutableListOf<Emoji>()
decoder.decodeStructure(descriptor) {
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
DECODE_DONE -> break@loop
else -> list.add(decodeSerializableElement(descriptor, index, Emoji::class.serializer()))
}
}
}
return list
}
override fun serialize(encoder: Encoder, value: List<Emoji>) {
error("Serialization is not supported")
}
}
Guilherme Delgado
01/31/2022, 5:48 PM@Provides
@Singleton
@RetrofitForEmojiList
@Suppress("JSON_FORMAT_REDUNDANT")
fun provideCustomRetrofit(client: OkHttpClient, @ApiUrl url: String): Retrofit {
return Retrofit.Builder()
.client(client)
.baseUrl(url)
.addConverterFactory(
Json {
serializersModule = SerializersModule { contextual(EmojiListSerializer) }
}.asConverterFactory("application/json".toMediaType())
)
.build()
}
Guilherme Delgado
01/31/2022, 5:49 PMcom.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
but the KSerializer is not called 🤷Guilherme Delgado
01/31/2022, 5:50 PM@GET(EMOJI)
suspend fun emojiList(): Response<Map<String, String>>
if I put a break point in the KSerializer
deserialize
method, is not calledGuilherme Delgado
01/31/2022, 5:50 PMGuilherme Delgado
01/31/2022, 6:10 PMDominaezzz
02/01/2022, 9:26 AMGuilherme Delgado
02/01/2022, 11:11 AMMap<String, Any>
it would?Dominaezzz
02/01/2022, 12:23 PMPaul Woitaschek
02/01/2022, 5:40 PMGuilherme Delgado
02/01/2022, 5:50 PMKSerializer
with a network response like I would do with moshi:
class EmojiAdapter : JsonAdapter<List<Emoji>>(), JsonAdapter.Factory {
override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<List<Emoji>>? {
if (type == Types.newParameterizedType(List::class.java, Emoji::class.java)) {
return this@EmojiAdapter
}
return null
}
@Throws(IOException::class)
override fun fromJson(reader: JsonReader): List<Emoji> {
val result = ArrayList<Emoji>()
reader.beginObject()
while (reader.hasNext()) {
result.add(Emoji(reader.nextName(), reader.nextString()))
}
reader.endObject()
return result
}
@Throws(IOException::class)
override fun toJson(writer: JsonWriter, value: List<Emoji>?) {
//not used
}
}
Paul Woitaschek
02/01/2022, 5:51 PMGuilherme Delgado
02/01/2022, 5:52 PMPaul Woitaschek
02/01/2022, 5:53 PM