Argonaut decoder how to change the type of one value in a case class

144 Views Asked by At

Id like to use the casecodecN or shapeless decoder for my case class, but one the fields has a different type when it is json.

consider, where b in json is a String like "1.23", but I want it as a Double.

case class Foo(a: Double, b: Double)

If I use casecodec2 it will error because b is a string

casecodec2(Foo.apply, Foo.unapply)("a", "b")

So I must manually write DecodeJson

DecodeJson[Foo](
  c =>
    for {
      a <- (c --\ "a").as[Double]
      b <- (c --\ "b").as[String].map(_.toDouble)
    } yield Foo(a, b)
)

This is ok for short case classes, but is tedious for bigger ones.

Is there a way I case use a derived Decoder but change just one values type ?

Thanks

1

There are 1 best solutions below

1
developer_hatch On

you can use an implicit convertion inside your class:

case class Foo(a: Double, b: Double){
   implicit def string2Double(s: String): Double = augmentString(s).toDouble
}