2016-12-04 90 views
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" 
) 

回答

3

瑟茜依賴於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都是年輕的項目,而且事情正在迅速發展。如果您被困在較早的版本中,並且這是因爲依賴於循環的庫,請聯繫Gitter,我們將嘗試與庫維護人員合作來更新內容。

+0

是的,這是訣竅。 –