You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中RestAssured反序列化POJO失败,输出值异常求助

问题分析与修复方案

一、打印逻辑错误

你当前打印的是Story()新建的空实例,而非RestAssured请求返回的stories变量,自然会输出字段默认值(null、0)。
修正后的打印代码:

println(stories?.title)
println(stories?.id)
println(stories?.items)

二、POJO结构与响应JSON不匹配(核心问题)

服务器响应的JSON层级是外层data对象 → data内包含stories数组,你的POJO完全没对应这个结构,且部分字段类型不匹配:

1. 新增根响应类

需要创建对应整个JSON结构的根类:

@JsonIgnoreProperties(ignoreUnknown = true)
class ApiResponse {
    var data: Data? = null
}

2. 修正Data类字段类型

服务器中stories是数组类型,你定义成了String?,改成List<Story>?:

@JsonIgnoreProperties(ignoreUnknown = true)
class Data {
    var stories: List<Story>? = null
}

3. 修正Story类字段类型

  • images在响应里是字符串数组,你定义成了String?,改为List<String>?
  • items在响应里是Item对象数组,你定义成了String?,改为List<Item>?

修正后的Story类:

@JsonIgnoreProperties(ignoreUnknown = true)
class Story {
    var id = 0
    var title: String? = null
    var description: String? = null
    var imageUrl: String? = null
    var imageUrlEco: String? = null
    var images: List<String>? = null // 修正为数组类型
    var style: String? = null
    var styleWeb: String? = null
    var link: String? = null
    var linkWeb: String? = null
    var linkEco: String? = null
    var buttonText: String? = null
    var dateFrom: String? = null
    var dateTo: String? = null
    var hidden: String? = null
    var isAuth: String? = null
    var onboardingType: String? = null
    var sortOrder = 0
    var type: String? = null
    var items: List<Item>? = null // 修正为Item数组类型
}

4. 给Item类添加注解

避免未知字段导致反序列化报错:

@JsonIgnoreProperties(ignoreUnknown = true)
class Item {
    var id = 0
    var title: String? = null
    var description: String? = null
    var detailedDescription: String? = null
    var imageUrl: String? = null
    var imageUrlWeb: String? = null
    var style: String? = null
    var styleWeb: String? = null
    var sortOrder = 0
}

三、修改请求提取逻辑

现在需要将响应反序列化为根类ApiResponse,再从中获取目标Story对象:

val apiResponse: ApiResponse = given()
    .log().all()
    .contentType(ContentType.JSON)
    .body(body)
.when()
    .log().all()
    .post(baseURI)
.then()
    .log().all()
    .extract().`as`(ApiResponse::class.java)

// 从数组中取第一个Story实例(根据业务需求调整)
val story = apiResponse.data?.stories?.firstOrNull()

// 打印目标字段
println(story?.title)
println(story?.id)
println(story?.items)

内容的提问来源于stack exchange,提问作者Gainor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:40:21