簡體   English   中英

是否可以使半自動解碼器考慮案例類字段的默認值?

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

是否可以使半自動解碼器考慮案例類字段的默認值?

以下代碼將失敗並顯示:

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

我認為馬戲團會考慮案例類字段的默認值為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是目前使其工作的唯一方法(缺少編寫自己的解碼器的功能)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM