https://kotlinlang.org logo
#ktor
Title
# ktor
j

Jorge Bo

04/06/2022, 4:16 PM
Hi , i have created a custom serializer to deserialize httpClient.get<Map<String, Market>(url) calls and then register it under json. What i can't figure out is how to set the generic types to the contextual mapping. As it is right now it does not allows me to register other contextual serializers for Map class. Any idea?
Copy code
json {
serializersModule = SerializersModule {
    contextual(Map::class) { MarketMapSerializer }
}
}

object MarketMapSerializer :
    JsonTransformingSerializer<Map<String, Market>>(MapSerializer(String.serializer(), Market.serializer())) {
    override fun transformDeserialize(element: JsonElement): JsonElement {
        return JsonObject(element.jsonObject.filterNot { (k, _) ->
            k == "token"
        })
    }
}
a

Aleksei Tirman [JB]

04/07/2022, 9:41 AM
Could you please share some code that doesn’t work as expected?
j

Jorge Bo

04/08/2022, 12:09 PM
sure, sorry for that late response. Basically i have two Map<String,Market> and Map<String,Station>, they are used for deserializing get calls
Copy code
json {
serializersModule = SerializersModule {
    contextual(Map::class) { MarketMapSerializer }
    contextual(Map::class) { StationMapSerializer }}
}

 object MarketMapSerializer :
        JsonTransformingSerializer<Map<String, Market>>(MapSerializer(String.serializer(), Market.serializer())) {
        override fun transformDeserialize(element: JsonElement): JsonElement {
            return JsonObject(element.jsonObject.filterNot { (k, _) ->
                k == "token"
            })
        }
    }

    object StationMapSerializer :
        JsonTransformingSerializer<Map<String, Station>>(MapSerializer(String.serializer(), Station.serializer())) {
        override fun transformDeserialize(element: JsonElement): JsonElement {
            return JsonObject(element.jsonObject.filterNot { (k, _) ->
                k == "token"
            })
        }
    }
Exception in thread "main" kotlinx.serialization.modules.SerializerAlreadyRegisteredException: Contextual serializer or serializer provider for class kotlin.collections.Map already registered in this module
a

Aleksei Tirman [JB]

04/08/2022, 3:00 PM
I suggest asking this question in #serialization channel.
👍 1
8 Views