【问题标题】:Parse Json using Circe and monocle lens使用 Circe 和单片眼镜解析 Json
【发布时间】:2016-12-04 11:36:01
【问题描述】:

我已经编写了这个示例代码

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

【问题讨论】:

    标签: json scala circe


    【解决方案1】:

    Circe 依赖于 Cats 库,该库最近删除了 cats.data.Xor,这是一种右偏的 Either 类类型。 Circe 0.5.0 及更早的版本使用cats.data.Xor 作为解析和解码的结果类型,但0.6.0+ 使用标准库的Either,因为Xor 已经消失了。

    将您的 circe 依赖项更新到 0.6.1 将使您的代码按照编写的方式工作。如果由于某种原因您卡在了早期版本的 circe 上,您需要调整您的代码以使用 Xor。不过,我建议坚持使用最新版本——circe 和 Cats 都是年轻的项目,而且进展很快。如果您因为某个库依赖于 circe 而卡在较早的版本上,请联系Gitter,我们将尝试与库维护者合作以进行更新。

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2019-09-15
      • 1970-01-01
      • 2021-06-09
      • 2017-10-03
      • 2020-06-02
      相关资源
      最近更新 更多