KTOR - 使用嵌套对象衍生 POST 请求正文

问题描述 投票:0回答:1

我有一个对象

@Serializable
data class Manufacturer(
    val uuid: String? = null,
    val name: String,
    val cars: List<CarModel> = emptyList()
)

用于将请求主体转换为内部对象。

CarModel
定义如下:

@Serializable
data class CarModel(val uuid: String? = null, val carType: String, val name: String)

现在我可以定义请求正文了

{
    "name": "Test Name",
}

请求成功,但是当我添加代表汽车型号的列表时,请求失败并出现错误:

Failed to convert request body to class

这是一个请求正文示例

{
    "name": "Manufacturer 1",
    "cars": [
        {
            "car_type": "Sedan",
            "name": "Car 1",
        },
        {
            "car_type": "Sedan",
            "name": "Car 2",
        },
    ]
}

ktor 似乎在反序列化嵌套对象时遇到问题,这就是为什么当我提供汽车列表时,它失败了,但当

CarModel
本身是可序列化时,我不知道如何解决这个问题,所以在理论,应该得到隐含的支持吗?我可以成功发送字符串列表,我只是无法处理自定义对象。

编辑:添加堆栈跟踪

2024-12-03 09:40:24.588 [eventLoopGroupProxy-4-3] TRACE io.ktor.routing.Routing - Trace for [manufacturer]
/, segment:0 -> SUCCESS @ /
  /ws, segment:0 -> FAILURE "Selector didn't match" @ /ws
  /json, segment:0 -> FAILURE "Selector didn't match" @ /json
  /manufacturers, segment:0 -> FAILURE "Selector didn't match" @ /manufacturers
  /manufacturer, segment:1 -> SUCCESS @ /manufacturer
    /manufacturer/(method:POST), segment:1 -> SUCCESS @ /manufacturer/(method:POST)
  /tag, segment:0 -> FAILURE "Selector didn't match" @ /tag
Matched routes:
  "" -> "manufacturer" -> "(method:POST)"
Route resolve result:
  SUCCESS @ /manufacturer/(method:POST)
2024-12-03 09:40:24.650 [eventLoopGroupProxy-4-3] TRACE i.k.server.engine.DefaultTransform - No Default Transformations found for class io.ktor.utils.io.ByteBufferChannel and expected type TypeInfo(type=class com.carapp.models.Manufacturer, reifiedType=class com.carapp.models.Manufacturer, kotlinType=com.carapp.models.Manufacturer) for call /manufacturer
2024-12-03 09:40:24.689 [eventLoopGroupProxy-4-3] TRACE i.k.s.p.statuspages.StatusPages - Call /manufacturer failed with cause io.ktor.server.plugins.BadRequestException: Failed to convert request body to class com.carapp.models.Manufacturer
2024-12-03 09:40:24.714 [eventLoopGroupProxy-4-3] TRACE i.k.s.p.statuspages.StatusPages - Executing (io.ktor.server.application.ApplicationCall, kotlin.Throwable) -> kotlin.Unit for exception io.ktor.server.plugins.BadRequestException: Failed to convert request body to class com.carapp.models.Manufacturer for call /manufacturer
2024-12-03 09:40:24.715 [eventLoopGroupProxy-4-3] TRACE i.k.s.p.c.ContentNegotiation - Skipping because body is already converted.

kotlin serialization deserialization ktor
1个回答
0
投票

事实证明,我在请求表示

Car.carType
时在 JSON 中使用的密钥不正确 - 当我应该发送
car_type
作为 JSON 密钥时,我正在发送
carType
,因此 正确 JSON 正文实际上是:

{
    "name": "Manufacturer 1",
    "cars": [
        {
            "carType": "Sedan",
            "name": "Car 1",
        },
        {
            "carType": "Sedan",
            "name": "Car 2",
        },
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.