我有一个运行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>
)