2

Given:

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))

How can I decode, i.e. JSON => Person, with the cursor's history? By history, I mean, I'd like to know that "foo" : "dunno" was not looked at/traversed.

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

2 Answers2

1

Unfortunately cursor history is discarded when the DecodeResult[T] object is built for success case.

The only solution I can think of (it is just a stub to explain you the concept) is to:

  • implement a custom 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)
}
  • implicitly extend ACursor adding an helper asH method
implicit class AHCursor(a: ACursor){
  def asH[A](implicit d: DecodeJson[A]): HistoryDecodeResult[A] = {
    HistoryDecodeResult(a.hcursor.map(_.history), a.as[A](d))
  }
}
  • override DecodeResult[T] composition methods within HistoryDecodeResult in order to accumulate the history:
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
  • obtain the HistoryDecodeResult from your decoding routine (you have to avoid Parse.decode) and ask for history.
Federico Pellegatta
  • 3,977
  • 1
  • 17
  • 29
0

According with argonaut cursor documentation, you could use the hcursor instead of a decoder, that way you can keep track of decoding process.