2017-04-02 47 views
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"未被查看/遍历。

回答

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)) 
    } 
} 
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)并要求提供历史。