2017-04-02 46 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)並要求提供歷史。