3

Below is shown the body of a Response of an http4k JavaHttpClient : '{"Hash":"QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH","Size":0,"CumulativeSize":6,"Blocks":0,"Type":"file"}

Which Kotlin module can be used to extract the values of the Fields "Hash" "Size" "Blocks" "Type" ?

Emile Achadde
  • 1,715
  • 3
  • 10
  • 22

2 Answers2

2

You need to add one of the supported JSON modules:

// 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"

Then you could extract the fields in a similar way:

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())
}

Some documentation is available here: https://www.http4k.org/api/org.http4k.format/-json/

KarolisL
  • 349
  • 1
  • 10
-4

Use Klaxon

build.gradle.kts :

   implementation("com.beust:klaxon:5.0.1")

kotlin module :

   import com.beust.klaxon.Klaxon
   data class MyData(val name: String)

   val result = Klaxon().parse<MyData>("""
       { "name": "John Doe",} 
   """)
  val name = result?.name

gives "John Doe"

Emile Achadde
  • 1,715
  • 3
  • 10
  • 22