1
我寫了這個示例代碼解析JSON使用瑟茜和單片眼鏡鏡片
package com.abhi
import io.circe._
import io.circe.optics.JsonPath._
object CirceTest extends App {
val id = root.id.long
val date = root.date.long
val input =
"""
|{
| "id" : 0,
| "childIds" : [
| 11, 12, 13
| ],
| "date" : 1480815583505
|}
""".stripMargin
parser.parse(input) match {
case Left(a) => println(s"failed ${a}")
case Right(json) =>
val myId = id.getOption(json).get
val myDate = date.getOption(json).get
println(s"id: ${myId} date: ${myDate}")
}
}
但這不會編譯事件
CirceTest.scala:26: constructor cannot be instantiated to expected type;
[error] found : scala.util.Right[A,B]
[error] required: cats.data.Xor[io.circe.ParsingFailure,io.circe.Json]
[error] case Right(json) =>
[error] ^
我也試過
val jsonEither = parser.parse(input)
if (jsonEither.isRight) {
val json = jsonEither.right.get
val myId = id.getOption(json).get
val myDate = date.getOption(json).get
println(s"id: ${myId} date: ${myDate}")
}
但是這也失敗
[error] CirceTest.scala:27: value right is not a member of cats.data.Xor[io.circe.ParsingFailure,io.circe.Json]
[error] val json = jsonEither.right.get
[error] ^
[error] one error found
我很驚訝。當我可以做isRight
那爲什麼編譯器會說我不能做right
?
這裏是我的build.sbt文件
name := "CirceTest"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"io.circe" %% "circe-core" % "0.5.1",
"io.circe" %% "circe-generic" % "0.5.1",
"io.circe" %% "circe-parser" % "0.5.1",
"io.circe" %% "circe-optics" % "0.5.1"
)
是的,這是訣竅。 –