【问题标题】:Decode w/ History on Success?解码成功的历史?
【发布时间】:2017-04-02 17:57:43
【问题描述】:

给定:

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 =&gt; Person,与光标的历史记录?通过历史,我的意思是,我想知道 "foo" : "dunno" 没有被查看/遍历。

【问题讨论】:

    标签: scala argonaut


    【解决方案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)并询问历史记录。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-11-21
        • 2010-11-06
        • 2015-08-18
        • 2015-04-12
        • 2012-05-14
        • 2013-12-25
        • 1970-01-01
        • 2016-08-25
        • 1970-01-01
        相关资源
        最近更新 更多