2

鉴于:

import argonaut._, Argonaut._

case class Person(name: String)

implicit def decode: DecodeJson[Person] =
  DecodeJson ( c => 
    for {
      name <- (c --\ "name").as[String]
    } yield Person(name)
  )

scala> Parse.decode[Person]("""{"name": "Bob", "foo": "dunno"}""")
res5: Either[Either[String,(String, argonaut.CursorHistory)],Person] = 
  Right(Person(Bob))

我怎样才能decode,即JSON => Person光标的历史?通过历史,我的意思是,我想知道没有"foo" : "dunno"被查看/遍历。

4

2 回答 2

1

不幸的是,当DecodeResult[T]为成功案例构建对象时,游标历史记录被丢弃。

我能想到的唯一解决方案(它只是一个向您解释这个概念的存根)是:

  • 实现自定义HistoryDecodeResult
class HistoryDecodeResult[A](
  val h: Option[CursorHistory], 
  result: \/[(String, CursorHistory),A]
) extends DecodeResult[A](result)

object HistoryDecodeResult{
  def apply[A](h: Option[CursorHistory], d: DecodeResult[A]) = new HistoryDecodeResult(h, d.result)
}
  • 隐式扩展ACursor添加辅助asH方法
implicit class AHCursor(a: ACursor){
  def asH[A](implicit d: DecodeJson[A]): HistoryDecodeResult[A] = {
    HistoryDecodeResult(a.hcursor.map(_.history), a.as[A](d))
  }
}
  • 覆盖其中的DecodeResult[T] 组合方法HistoryDecodeResult以累积历史记录:
override def map[B](f: A => B): HistoryDecodeResult[B] = 
  HistoryDecodeResult(h, super.map(f))

//Accumulate history `h` using `CursorHistory.++` if flat-mapping with another HistoryDecodeResult
override def flatMap[B](f: A => DecodeResult[B]): HistoryDecodeResult[B] = ???

... //Go on with other methods
  • 从你的解码例程中获取HistoryDecodeResult(你必须避免Parse.decode)并询问历史。
于 2017-04-10T09:35:53.777 回答
0

根据argonaut cursor documentation,您可以使用 hcursor 代替解码器,这样您就可以跟踪解码过程。

于 2017-04-11T19:07:12.657 回答