下面显示了http4k JavaHttpClient的响应主体:'{"哈希":"QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH","大小":0,"累积大小":6,"块":0、"类型":"文件"}
哪个Kotlin模块可以用于提取字段"Hash"Size"Blocks"Type"的值?
您需要添加一个受支持的JSON模块:
// Argo:
implementation group: "org.http4k", name: "http4k-format-argo", version: "4.33.1.0"
// Gson:
implementation group: "org.http4k", name: "http4k-format-gson", version: "4.33.1.0"
// Jackson:
implementation group: "org.http4k", name: "http4k-format-jackson", version: "4.33.1.0"
// Klaxon:
implementation group: "org.http4k", name: "http4k-format-klaxon", version: "4.33.1.0"
// Moshi:
implementation group: "org.http4k", name: "http4k-format-moshi", version: "4.33.1.0"
// KotlinX Serialization:
implementation group: "org.http4k", name: "http4k-format-kotlinx-serialization", version: "4.33.1.0"
然后你可以用类似的方式提取字段:
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.format.Jackson.asJsonObject
val body = """
{"Hash":"QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH","Size":0,"CumulativeSize":6,"Blocks":0,"Type":"file"}
""".trimIndent()
val response = Response(Status.OK).body(body)
response.bodyString().asJsonObject().let {
require(it.get("Hash").textValue() == "QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH")
require(it.get("Size").intValue() == 0)
require(it.get("CumulativeSize").intValue() == 6)
require(it.get("Blocks").intValue() == 0)
require(it.get("Type").textValue() == "file")
println(it.get("Hash").textValue())
}
此处提供了一些文档:https://www.http4k.org/api/org.http4k.format/-json/
使用Klaxon
build.gradle.kts:
implementation("com.beust:klaxon:5.0.1")
kotlin模块:
import com.beust.klaxon.Klaxon
data class MyData(val name: String)
val result = Klaxon().parse<MyData>("""
{ "name": "John Doe",}
""")
val name = result?.name
给出"John Doe">