使用kotlinx.serialization

我有一个运行kotlinx.serialization的Ktor服务器,因为它是json(de)serializer 我向Ktor发送了这样的消息:

{
  "Brick(partNumber=004229,partName=Sticker Sheet for Set 295-1,dataSource=Rebrickable,brickImage=null,categoryID=58)": 5
}

这是一对Int和此类:

import kotlinx.serialization.Serializable

@Serializable
data class Brick(
    val partNumber: String,val partName: String,val dataSource: String,val brickImage: String?,val categoryID: Int?
)

但是我得到这个错误

kotlinx.serialization.json.JsonDecodingException: Invalid JSON at 0: Expected '[,kind: MAP'
    at kotlinx.serialization.json.internal.JsonReader.fail(JsonReader.kt:293)

对我来说,这意味着kotlinx.serialization需要map类的语法不同。这对我来说很奇怪。当我将类型更改为List>时,它将引发相同的异常,但使用LIST而不是MAP。 编辑:经过进一步检查,它期望在行的开头使用[而不是{。 我的(部分)应用程序实现

fun Application.module(testing: Boolean = false) {
    install(ContentNegotiation) { serialization() }
    routing {
        route("user") {
            route("brick") {
                post {
                    call.request.queryParameters["username"]
                        ?.let { userRepository.login(it) } // Someone else is still working login nvm this
                        ?.let { user ->
                            val bricks = call.receive<Map<Brick,Int>>() // This throws an error
                            userRepository.addBricks(user,bricks)
                            call.respond(HttpStatusCode.OK)
                        }
                        ?: call.respond(HttpStatusCode.Unauthorized)
                }
            }
        }
    }
}

发送类(使用GSON)的android改造函数:

    @POST("/user/brick")
    suspend fun setBricksAmounts(
        @Query("username")
        username: String,@Body
        brickAmounts: Map<Brick,Int>
    )
mmcy588 回答:使用kotlinx.serialization

我认为使用类作为键在kotlinx序列化中不起作用 看起来该类刚刚被序列化为字符串以用作键

相反,您可以以Map<String,Int>的形式接收它 然后运行

bricks.mapKeys { (jsonString,number) ->
   Json(JsonConfiguration.Stable).parse(Brick.Serializer,jsonString)
}

或等效的杰克逊代码(如果需要)

本文链接:https://www.f2er.com/2547207.html

大家都在问