plokhotnyuk / jsoniter-scala

Scala macros for compile-time generation of safe and ultra-fast JSON codecs + circe booster
MIT License
750 stars 99 forks source link

Provide codec for standard class Duration #1212

Open DavidPerezIngeniero opened 1 month ago

DavidPerezIngeniero commented 1 month ago

When trying:

case class ConfiguracionCola(
                              nombre: String,
                              maxWorkers: Int,
                              jobTimeout: Duration,
                              observaciones: String,
                              prioritaria: Boolean,
                              grupo: String,
                              httpTimeout: Duration,
                              httpTtl: Duration,
                              httpMaxReintentos: Int
                            )

object ConfiguracionCola:
   given JsonValueCodec[ConfiguracionCola:] = make

I receive this strange error message:

Local child symbols are not supported, please consider change 'scala.concurrent.duration.Duration.Infinite' or 
implement a custom implicitly accessible codec

For me, the error message is not explanatory enough. Should I write a custom serializer for Durations?

plokhotnyuk commented 1 month ago

@DavidPerezIngeniero Yes, 'scala.concurrent.duration.Duration is not supported yet for automatic derivation of codecs.

So, if using of java.time.Duration is not an option, then need to write a custom codec.

DavidPerezIngeniero commented 1 month ago

Thanks!

Possible implementation:

  given JsonValueCodec[Duration] with
    override def decodeValue(in: JsonReader, default: Duration): Duration =
      val l = in.readLong()
      if (l == -1) Duration.Inf else Duration.fromNanos(l)

    override def encodeValue(x: Duration, out: JsonWriter): Unit =
      out.writeVal(if (x == Duration.Inf) -1 else x.toNanos)

    override def nullValue: Duration = Duration.Inf