Search code examples
json-deserializationktor

ktor dynamic keys serialization and json preprosesing


Is there anyway in Ktor to alter a json before deserialization process? In the example below there is a json with dynamic keys in which i need to remove the "token" key as it is of a string type instead of an object type as the other keys. When i urn the code i get the following error:

Exception in thread "main" kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject as the serialized body of shell.remoting.Market, but had class kotlinx.serialization.json.JsonLiteral

I'm not sure if there is another better way to do it. Any suggestion will be appreciated, thanks

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

@Serializable
data class Market(
    val stations: List<Station>,
)

@Serializable
data class Station(
    @JsonNames("iata_code")
    val iataCode: String,
    val destinations: List<String>,
)


fun main() {
    val jsonString = """
        {
            "Republica Dominicana": {
                "stations": [
                    {
                        "iata_code": "PUJ",
                        "destinations": [
                            "ADZ",
                            "BAQ",
                            "VVC"
                        ]
                    }
                ]
            },
            "Brasil": {
                "stations": [
                    {
                        "iata_code": "AJO",
                        "destinations": [
                            "ADZ",
                            "BAQ",
                            "VVC"
                        ]
                    }
                ]
            },
            "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkb3RSRVogQVBJIiwianRpIjoiYTVhZDM4NmYtOGViNy0yOWQ5LWZkMGYtM2Q3MzQwZmRhOGI2IiwiaXNzIjoiZG90UkVaIEFQSSJ9.V2YfXCt9r7Tzae9SYSoj-qIyxjRc9YoE2XPoIQQNI9U"
        }
    """.trimIndent()
    println(
        Json.decodeFromString(
            MarketMapSerializer,
            jsonString
        )
    )
}

Solution

  • Just replace transformSerialize with the transformDeserialize since you're doing deserialization.