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

Kotlin http4k:从Response体提取JSON字段的方法及适用模块

Great question! When working with http4k in Kotlin, you have a couple of clean ways to extract JSON fields from a Response body—using either type-safe data classes with serialization or direct JSON parsing. The most common (and recommended) modules for this are http4k-format-jackson or http4k-format-moshi, both of which integrate seamlessly with http4k's APIs.

Let's walk through both approaches using your sample response:

{"Hash":"QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH","Size":0,"CumulativeSize":6,"Blocks":0,"Type":"file"}

This is the cleanest method because it leverages Kotlin's type system to avoid runtime errors. First, add the dependency (we'll use Jackson here, but Moshi works similarly):

For Gradle:

implementation("org.http4k:http4k-format-jackson:4.40.0.0") // Use latest version available

Then define a data class that matches your JSON structure:

data class FileMetadata(
    val Hash: String,
    val Size: Int,
    val CumulativeSize: Int,
    val Blocks: Int,
    val Type: String
)

Now deserialize the response body into this data class:

import org.http4k.client.JavaHttpClient
import org.http4k.core.Response
import org.http4k.format.Jackson.auto

// Fetch your response using JavaHttpClient
val response: Response = JavaHttpClient().get("your-target-api-url")

// Auto-generate the decoder for the data class
val fileMetadataDecoder = auto<FileMetadata>()

// Convert the response body to your strongly-typed data class
val metadata = fileMetadataDecoder(response.body)

// Access the fields directly with full type safety
println("Hash: ${metadata.Hash}")
println("Size: ${metadata.Size}")
println("Blocks: ${metadata.Blocks}")
println("Type: ${metadata.Type}")

2. Direct JSON Parsing (No Data Class)

If you don't want to define a data class, you can parse the JSON string directly into a JsonObject and access fields by name:

import org.http4k.core.Response
import org.http4k.format.Jackson.parseJson

val response: Response = JavaHttpClient().get("your-target-api-url")
val jsonBody = response.bodyString()

// Parse the raw string into a manipulable JsonObject
val json = jsonBody.parseJson()

// Extract individual fields using their keys
val hash = json["Hash"].asText()
val size = json["Size"].asInt()
val blocks = json["Blocks"].asInt()
val type = json["Type"].asText()

Choosing Between Modules

  • Jackson: A mature, widely-used JSON library with strong support for complex structures and edge cases.
  • Moshi: A lighter, Kotlin-first alternative that prioritizes concise code and avoids some of Jackson's legacy quirks.

Either module will let you extract the fields you need from your response. The data class approach is almost always better for long-term maintainability and type safety, though!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:42:38