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

如何在Ktor Kotlin中用Kotlinx序列化获取嵌套JSON属性且无需数据类

问题:Kotlin/Ktor中解析Google Books API JSON并提取title(不使用数据类)

我正在用Kotlin和Ktor开发Web应用,需要解析Google Books API返回的嵌套JSON,提取其中的title值存储。使用Kotlinx Serialization进行序列化,但希望避免创建数据类。

API返回的简化JSON结构如下:

{"kind": "books#volumes","totalItems": 795,"items": [{"kind": "books#volume","id": "zYw3sYFtz9kC","etag": "ylNs2Stlgis","selfLink": "https://www.googleapis.com/books/v1/volumes/zYw3sYFtz9kC","volumeInfo": {"title": "The Contemporary Thesaurus of Search Terms and Synonyms","subtitle": "A Guide for Natural Language Computer Searching","authors": ["Sara D. Knapp"],"publisher": "Greenwood Publishing Group","publishedDate": "2000"}}]}

目前已通过代码获取到items字段,但无法进一步访问到title。现有调用API的代码如下(Routing.kt):

val response: HttpResponse = client.get("https://www.googleapis.com/books/v1/volumes?q=isbn:$isbn")
println(response.status)
val stringBody: String = response.body()
val json: Map<String, JsonElement> = Json.parseToJsonElement(stringBody).jsonObject
//println(json)
val item = json["items"]
//println(item)

请问如何实现提取title的需求?


解决方案

可以通过Kotlinx Serialization的JsonElement相关API逐层解析嵌套结构,具体步骤如下:

  • 将items转换为JsonArray:items是数组类型,需要先把json["items"]转为JsonArray,再取出第一个元素(如果存在)。
  • 解析volumeInfo对象:从单个item中提取volumeInfo对应的JsonObject。
  • 提取title字符串:从volumeInfo中取出title字段的值。

同时要注意空值处理,避免API返回空数组或缺失字段导致的异常。

修改后的完整代码示例:

val response: HttpResponse = client.get("https://www.googleapis.com/books/v1/volumes?q=isbn:$isbn")
println(response.status)
val stringBody: String = response.body()
val jsonObject = Json.parseToJsonElement(stringBody).jsonObject

// 解析items数组并取第一个元素
val itemsArray = jsonObject["items"]?.jsonArray
val firstItem = itemsArray?.firstOrNull()?.jsonObject

// 解析volumeInfo并提取title
val title = firstItem?.get("volumeInfo")?.jsonObject?.get("title")?.jsonPrimitive?.content

// 打印或存储title
println("提取到的标题:$title")

代码说明:

  • jsonObject["items"]?.jsonArray:安全地将items字段转为JsonArray,避免空指针。
  • firstOrNull():获取数组第一个元素,若数组为空则返回null。
  • 逐层访问volumeInfo和title:每一步都用?.做安全调用,确保在字段缺失时不会崩溃。
  • jsonPrimitive?.content:将JsonPrimitive类型的title转为字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:25:17