我有一个API,它返回一个列表作为响应:
这将以列表格式返回响应字符串,如下所示。[["item", 1, "other item"], ["item", 2, "other item"]]
我该如何将其转换为列表格式,而非字符串数据类型?
我有一个API,它返回一个列表作为响应:
这将以列表格式返回响应字符串,如下所示。[["item", 1, "other item"], ["item", 2, "other item"]]
// 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")
}
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"]]
}
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,
)
Kanojo, Okarishimasu 2nd Season
),这会阻止使用.split(",")
。否则,这将是一个简单的任务。 - yezper