本文介绍了Circe 解码到由多个案例类扩展的密封特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我以前见过类似的问题,但没有一个有效.我认为他们会问一些不同的问题,所以我在这里问.我在一个文件中有这样的东西:

I've seen similar questions before, but none of them have worked. I think that they ask something different so I'm asking here.I have something like this in one file:

sealed trait Thing
case class SomeThing() extends Thing
case class OtherThing() extends Thing

并在另一个文件中:

val str = //valid json
val decoded = decode[Thing](str)
println(decoded)

我得到:

Left(DecodingFailure(...))

如果我这样做了,这会起作用:

This works if I did:

val str = //valid json
val decoded = decode[SomeThing](str)
println(decoded)

推荐答案

你可以使用 circe-generic-extras 并为你的 jsons 添加类型鉴别器:

you can use circe-generic-extras and add type discriminator for your jsons:

在你的 build.sbt 中:

In your build.sbt:

libraryDependencies ++= Seq(
  "io.circe" %% "circe-generic-extras" % "0.12.2",
  "io.circe" %% "circe-parser" % "0.12.2"
)

现在让我们定义我们的类并对其进行序列化+反序列化:

Now let's define our classes and serialize + deserialize them:

sealed trait Thing
case class SomeThing() extends Thing
case class OtherThing() extends Thing

import io.circe.generic.extras.auto._
import io.circe.generic.extras.Configuration
import io.circe.syntax._
import io.circe.parser

implicit val customConfig: Configuration =
  Configuration.default.withSnakeCaseMemberNames.withDiscriminator("type")

val thing: Thing = SomeThing()

// serialize thing to json
val jsString: String = thing.asJson.spaces2
println(s"serialized $thing to:\n$jsString")
/* serialized SomeThing() to:
{
"type" : "SomeThing"
}
*/

// deserialize json to thing
val errorOrMyTrait: Either[io.circe.Error, Thing] = parser.decode[Thing](jsString)

println(errorOrMyTrait) // Right(SomeThing())

注意,现在序列化的json包含密封类的类型

Notice that now the serialized json contains the type of the sealed class

这篇关于Circe 解码到由多个案例类扩展的密封特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 01:26