【发布时间】:2020-08-12 16:19:24
【问题描述】:
我正在使用 circe 文档中的示例 ADT 来重现我在 JSON 解码方面遇到的问题。
为此,我使用 ShapesDerivation :
scala> object ShapesDerivation {
|
| implicit def encodeAdtNoDiscr[Event, Repr <: Coproduct](implicit
| gen: Generic.Aux[Event, Repr],
| encodeRepr: Encoder[Repr]
| ): Encoder[Event] = encodeRepr.contramap(gen.to)
|
| implicit def decodeAdtNoDiscr[Event, Repr <: Coproduct](implicit
| gen: Generic.Aux[Event, Repr],
| decodeRepr: Decoder[Repr]
| ): Decoder[Event] = decodeRepr.map(gen.from)
|
| }
defined object ShapesDerivation
要解码的 ADT 由两个值组成:一个简单的案例类和另一个我有专用编码器/解码器的值(在最小的例子中重现我真正遇到的问题):
scala> :paste
// Entering paste mode (ctrl-D to finish)
sealed trait Event
object Event {
case class Foo(i: Int) extends Event
case class Bar(f : FooBar) extends Event
case class FooBar(x : Int)
implicit val encoderFooBar : Encoder[FooBar] = new Encoder[FooBar] {
override def apply(a: FooBar): Json = Json.obj(("x", Json.fromInt(a.x)))
}
implicit val decodeFooBar: Decoder[FooBar] = new Decoder[FooBar] {
override def apply(c: HCursor): Result[FooBar] =
for {
x <- c.downField("x").as[Int]
} yield FooBar(x)
}
}
然后,当我尝试解码这样的简单值时,它运行良好:
scala> import ShapesDerivation._
import ShapesDerivation._
scala> decode[Event](""" { "i" : 10 }""")
res1: Either[io.circe.Error,Event] = Right(Foo(10))
但是,如果我尝试解码应该是包含 Foobar 的 Bar 的内容,则会出现解码失败:
scala> decode[Event](""" { "x" : 10 }""")
res2: Either[io.circe.Error,Event] = Left(DecodingFailure(CNil, List()))
但这一个有效,因为我明确地输入了案例类字段名称:
scala> decode[Event](""" { "f" : { "x" : 10 }}""")
res7: Either[io.circe.Error,Event] = Right(Bar(FooBar(10)))
我不放什么案例类字段,直接放 JSON,但我认为不可能实现这样的行为。我认为不可能的原因是,如果没有该字段,它将如何知道匹配好的案例类,但我想确定 circe 没有办法做到这一点
【问题讨论】: