Scala 如何将Circe Optics与解码结合使用
我用的是这样的circe光学系统Scala 如何将Circe Optics与解码结合使用,scala,circe,Scala,Circe,我用的是这样的circe光学系统 import io.circe.parser._ import io.circe.optics._ import io.circe.optics.JsonPath._ val json = parse("""{"response": {"person": {"firstname": "foo", "lastname":"bar"}}}""").right.get 现在我想以字符串形式提取整个person对象。。。从这个类似json的 val p = root
import io.circe.parser._
import io.circe.optics._
import io.circe.optics.JsonPath._
val json = parse("""{"response": {"person": {"firstname": "foo", "lastname":"bar"}}}""").right.get
现在我想以字符串形式提取整个person对象。。。从这个类似json的
val p = root.response.person.string
然后把它解码成一个case类,比如
case class Person(firstname: String, lastname: String)
decode[Person](p.getOption(json).get)
但它不起作用,因为root.response.person.string
返回null。我认为它只适用于实际的字符串和整数列
那么circe optics可以用来提取json的整个部分吗(例如json中的person对象)?然后该部分被解码成一个case类?这就完成了。不需要在两者之间设置字符串,只需使用
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)
}