ktor 动态密钥序列化和 json 预处理
ktor dynamic keys serialization and json preprosesing
在反序列化过程之前,Ktor 是否有改变 json 的方法?在下面的示例中,有一个带有动态键的 json ,我需要删除其中的“token”键,因为它是字符串类型而不是其他键的对象类型。
当我运行代码时出现以下错误:
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
我不确定是否还有其他更好的方法。任何建议将不胜感激,谢谢
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
)
)
}
只需将 transformSerialize
替换为 transformDeserialize
,因为您正在进行反序列化。
在反序列化过程之前,Ktor 是否有改变 json 的方法?在下面的示例中,有一个带有动态键的 json ,我需要删除其中的“token”键,因为它是字符串类型而不是其他键的对象类型。 当我运行代码时出现以下错误:
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
我不确定是否还有其他更好的方法。任何建议将不胜感激,谢谢
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
)
)
}
只需将 transformSerialize
替换为 transformDeserialize
,因为您正在进行反序列化。