gpt4 book ai didi

scala - 如何一起使用 Circe Optics 和 Decode

转载 作者:行者123 更新时间:2023-12-01 09:50:02 25 4
gpt4 key购买 nike

我正在使用这样的圆形光学器件

import io.circe.parser._
import io.circe.optics._
import io.circe.optics.JsonPath._

val json = parse("""{"response": {"person": {"firstname": "foo", "lastname":"bar"}}}""").right.get

现在我想从这个 json 中以字符串形式提取整个人对象......

val p = root.response.person.string

然后将它解码成一个类

case class Person(firstname: String, lastname: String)
decode[Person](p.getOption(json).get)

但它不起作用,因为 root.response.person.string 返回 null。我认为它只适用于实际的字符串和整数列。

那么可以使用 circe optics 提取整个 json 部分(例如 json 中的 person 对象)吗?然后该部分被解码为案例类?

最佳答案

这样就搞定了。无需获取中间的字符串,只需使用 Json

object Some extends App {

import io.circe.optics.JsonPath._
import io.circe.parser._
import io.circe._
import io.circe.generic.semiauto._

val json = parse("""{"response": {"person": {"firstname": "foo", "lastname":"bar"}}}""").right.get

// this is just a lense to the person, not the person yet
val personJsonPath = root.response.person.json

case class Person(firstname: String, lastname: String)
implicit val personDecoder: Decoder[Person] = deriveDecoder[Person]

val maybePerson = personJsonPath
// here you get the person out
.getOption(json)
// transforming json directly to case class, error handling should not be done like this ;)
.map(_.as[Person].fold(throw _, identity))

println(maybePerson)
}

关于scala - 如何一起使用 Circe Optics 和 Decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50034649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com