如何在 Kotlin 中从响应中获取列表

3

这对您有用吗?https://dev59.com/tXA75IYBdhLWcg3wOGPS - HoRn
1
我会使用kotlinx.serialization.json进行反序列化。 - Matt Groth
问题在于,API响应中的某些字符串包含逗号符号(例如Kanojo, Okarishimasu 2nd Season),这会阻止使用.split(",")。否则,这将是一个简单的任务。 - yezper
很遗憾,响应不是application/json。 - yezper
1
@inoflow 原始问题中链接显示的原始字符串是格式正确的 JSON。反序列化该原始字符串应该可以正常工作。 - Matt Groth
显示剩余2条评论
1个回答

1
一种方法是使用 Kotlinx Serialization。它没有直接支持元组,但可以将输入解析为JSON数组,然后手动映射到特定的数据类型(如果我们做出一些假设)。
首先添加Kotlinx序列化的依赖项。
// build.gradle.kts

plugins {
  kotlin("jvm") version "1.7.10"
  kotlin("plugin.serialization") version "1.7.10" 
  // the KxS plugin isn't needed, but it might come in handy later!
}

dependencies {
  implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0")
}

请参阅 Kotlinx Serialization README 以获取Maven说明。
然后,我们可以使用JSON映射器来解析API请求的结果。
import kotlinx.serialization.json.*

fun main() {
  val inputJson = """ 
     [["item", 1, "other item"], ["item", 2, "other item"]]
  """.trimIndent()

  // Parse, and use .jsonArray to force the results to be a JSON array
  val parsedJson: JsonArray = Json.parseToJsonElement(inputJson).jsonArray

  println(parsedJson)
  // [["item",1,"other item"],["item",2,"other item"]]
}

“手动将这个JsonArray对象映射到数据类比尝试设置自定义的Kotlinx序列化器要容易得多。”
import kotlinx.serialization.json.*

fun main() {
  val inputJson = """ 
     [["item", 1, "other item"], ["item", 2, "other item"]]
  """.trimIndent()

  val parsedJson: JsonArray = Json.parseToJsonElement(inputJson).jsonArray

  val results = parsedJson.map { element ->
    val data = element.jsonArray
    // Manually map to the data class. 
    // This will throw an exception if the content isn't the correct type...
    SearchResult(
      data[0].jsonPrimitive.content, 
      data[1].jsonPrimitive.int,
      data[2].jsonPrimitive.content,
    )
  }

  println(results)
  // [SearchResult(title=item, id=1, description=other item), SearchResult(title=item, id=2, description=other item)]

}

data class SearchResult(
  val title: String,
  val id: Int,
  val description: String,
)

我定义的解析是严格的,假定列表中的每个元素也将是包含3个元素的列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接