Scala Circe deriveUnwrapped 值类缺失JSON字段无法解码为None
问题根因定位
当前代码的解码失败来自两层逻辑的错位:
- 解码
{"name":null}时,JSON中name字段是实际存在的,Circe会将字段值null传递给自定义的customStringDecoder:原生Option[String]解码器遇到null值会返回None,经过自定义的空串过滤逻辑转换后仍为CustomString(None),因此断言可以正常通过。 - 解码空JSON
{}时,JSON结构中完全不存在name字段。当前使用的io.circe.generic.semiauto.deriveCodec是普通派生解码器,默认将所有case class字段视为必填项,遇到缺失字段会直接抛出“缺失目标字段”的解码错误,根本不会触发后续自定义解码器的逻辑,自然无法得到预期的noneTestString实例。
代码调整方案
全程保留原有自定义值类“空串转None、null转None”的业务逻辑,仅从两处修改解决问题:
- 给目标类字段配置缺失时的默认值:将
TestString的name字段加上默认值,当JSON中缺失该字段时,会自动用默认值兜底:final case class TestString(name: CustomString = CustomString(None)) - 替换支持默认值兜底的解码器派生逻辑:放弃普通的
deriveCodec方法,改用circe-generic-extras的配置化派生能力,开启“缺失字段自动使用类默认值兜底”的配置:// 配置Circe解码行为:缺失字段时自动取case class定义的参数默认值 implicit val circeConfig: Configuration = Configuration.default.withDefaults // 替换原来的普通deriveCodec,使用配置化的codec派生 implicit val testStringCodec: Codec[TestString] = deriveConfiguredCodec[TestString]
调整后完整可运行的脚本
import $ivy.`io.circe::circe-generic:0.13.0`, io.circe._, io.circe.generic.auto._, io.circe.syntax._, io.circe.generic.JsonCodec import $ivy.`io.circe::circe-generic-extras:0.13.0`, io.circe.generic.extras._, io.circe.generic.extras.semiauto._ import $ivy.`io.circe::circe-parser:0.13.0`, io.circe.parser._ final case class CustomString(value: Option[String]) extends AnyVal // 给name字段加上缺失时的默认值 final case class TestString(name: CustomString = CustomString(None)) implicit val customStringDecoder: Decoder[CustomString] = deriveUnwrappedDecoder[CustomString].map(ss => CustomString(ss.value.flatMap(s => Option.when(s.nonEmpty)(s)))) implicit val customStringEncoder: Encoder[CustomString] = deriveUnwrappedEncoder[CustomString] // 开启缺失字段用类默认值兜底的配置 implicit val circeConfig: Configuration = Configuration.default.withDefaults // 使用配置化的codec替换原来的普通派生 implicit val testStringCodec: Codec[TestString] = deriveConfiguredCodec[TestString] val testString = TestString(CustomString(Some("test"))) val emptyTestString = TestString(CustomString(Some(""))) val noneTestString = TestString(CustomString(None)) val nullJson = """{"name":null}""" val emptyJson = """{}""" assert(testString.asJson.noSpaces == """{"name":"test"}""") assert(emptyTestString.asJson.noSpaces == """{"name":""}""") assert(noneTestString.asJson.noSpaces == nullJson) assert(noneTestString.asJson.dropNullValues.noSpaces == emptyJson) assert(decode[TestString](nullJson).exists(_ == noneTestString)) // 原有通过的断言保持有效 assert(decode[TestString](emptyJson).exists(_ == noneTestString)) // 原来失败的断言现在可正常通过
注意:普通的
circe.generic.semiauto.deriveXxx系列方法不会读取case class的参数默认值作为解码兜底,必须使用circe-generic-extras提供的deriveConfiguredXxx系列方法,且在作用域内显式配置开启withDefaults,才能实现缺失字段的默认值填充逻辑。
内容的提问来源于stack exchange,提问作者Mihai Soloi
相关产品推荐
相关产品推荐

