`circe` Level type Json => A Function?

Using circeor argonaut, as I can write Json => A(note - Jsonmay not be a type name), where it Ais specified by the class SSN:

  // A USA Social Security Number has exactly 8 digits.
  case class SSN(value: Sized[List[Nat], _8])

?

pseudo code:

// assuming this function is named f

f(JsArray(JsNumber(1)))will not A, because its size is 1, whereas

f(JsArray(JsNumber(1), ..., JsNumber(8))) === SSN(SizedList(1,...,8))

+4
source share
1 answer

circe does not provide (currently) instances for Sized, but it probably should be. In any case, you can write your own pretty straight forward:

import cats.data.Xor
import io.circe.{ Decoder, DecodingFailure }
import shapeless.{ Nat, Sized }
import shapeless.ops.nat.ToInt
import shapeless.syntax.sized._

implicit def decodeSized[L <: Nat, A](implicit
  dl: Decoder[List[A]],
  ti: ToInt[L]
): Decoder[Sized[List[A], L]] = Decoder.instance { c =>
  dl(c).flatMap(as =>
    Xor.fromOption(as.sized[L], DecodingFailure(s"Sized[List[A], _${ti()}]", c.history))
  )
}

I limited it to a view List, but you could make it more general if you want.

SSN, ( , Int Nat , , - Nat, ):

case class SSN(value: Sized[List[Int], Nat._8])

implicit val decodeSSN: Decoder[SSN] = Decoder[Sized[List[Int], Nat._8]].map(SSN(_))

:

scala> import io.circe.jawn.decode
import io.circe.jawn.decode

scala> decode[SSN]("[1, 2, 3, 4, 5, 6, 7, 8]")
res0: cats.data.Xor[io.circe.Error,SSN] = Right(SSN(List(1, 2, 3, 4, 5, 6, 7, 8)))

scala> decode[SSN]("[1, 2, 3, 4, 5, 6, 7]")
res1: cats.data.Xor[io.circe.Error,SSN] = Left(DecodingFailure(Sized[List[A], _8], List()))

Json => SSN, :

val f: Json => SSN = Decoder[SSN].decodeJson(_).valueOr(throw _)

.

+5

Source: https://habr.com/ru/post/1652698/


All Articles