是否可以让半自动解码器考虑 case class 字段的默认值?

Is that possible to make semiauto decoders consider default values for case class fields?

是否可以让半自动解码器考虑 case class 字段的默认值?

以下代码将失败:

Left(DecodingFailure(Attempt to decode value on failed cursor, List(DownField(isActive))))

我认为 circe 会考虑 case class 字段的默认值 isActive

case class Person(
  id: Option[Int] = None,
  name: String,
  isActive: Boolean = true
)

implicit val personJsonDecoder: Decoder[Person] = deriveDecoder

val rawJson = """
{
  "name": "Geovanny Junio"
}
"""

val r = for {
  j <- parse(rawJson)
  p <- j.as[Person]
} yield p

println(r)

是的,但您需要 circe-generic-extras:

import io.circe.Decoder
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveDecoder

case class Person(
  id: Option[Int] = None,
  name: String,
  isActive: Boolean = true
)

object Person {
  implicit val personConfig: Configuration =
    Configuration.default.withDefaults
  implicit val personJsonDecoder: Decoder[Person] = deriveDecoder
}

然后:

scala> io.circe.jawn.decode[Person]("""{"name": "Geovanny Junio"}""")
res0: Either[io.circe.Error,Person] = Right(Person(None,Geovanny Junio,true))

我一直打算将这个功能添加到 circe-derivation 中,但没有时间,所以 circe-generic-extras 是目前让它工作的唯一方法(除了编写自己的解码器) .