简体   繁体   English

是否可以使半自动解码器考虑案例类字段的默认值?

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

Is that possible to make semiauto decoders consider default values for case class fields? 是否可以使半自动解码器考虑案例类字段的默认值?

The following code will fail with: 以下代码将失败并显示:

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

I thought circe would consider the default value for the case class field 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)

Yes, but you'll need circe-generic-extras: 是的,但是您需要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
}

And then: 接着:

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

I've been intending to add this functionality to circe-derivation, but haven't had time, so circe-generic-extras is the only way to make it work for now (short of writing your own decoder). 我一直打算将此功能添加到circe-derivation中,但还没有时间,因此circe-generic-extras是目前使其工作的唯一方法(缺少编写自己的解码器的功能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Scala Jackson对象映射器在case类中设置null而不是默认值 - Scala Jackson object mapper setting null instead of default values in case class 具有默认参数的通用 case 类的 Circe 编码器 - Circe encoder for generic case class with default parameters Circe:将案例类主体字段序列化为JSON - Circe : Serialize case class body fields to JSON 在这种情况下是否可以减少读取JSON值的功能 - Is it possible to reduce the functions for reading JSON values in this case 为案例类播放json读取和默认参数? - Play json Read and Default parameters for case class? 使用playframework将json数组解析为scala中的case类,json中的字段与case类中的字段不匹配 - Parse json array to a case class in scala using playframework with the fields in json not matching the fields in case class Java Reflection:避免使用默认值的字段 - Java Reflection : avoid fields with default values 如何为案例类定义一个“写入”,它将生成嵌套的自定义字段? - How to define a `Write` for an case class which will generate nested custom fields? JSON格式不足以解析具有&gt; 22个字段的案例类吗? - Is JSON formatting not enough for parsing case class having > 22 fields? 自定义Json使用组合器写入 - 不需要案例类的所有字段 - Custom Json Writes with combinators - not all the fields of the case class are needed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM