Circe解码为由多个案例类扩展的密封特征

时间:2018-05-21 22:40:53

标签: scala circe

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

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(...))

如果我这样做,这是有效的:

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

3 个答案:

答案 0 :(得分:1)

我必须编写自己的编码器和解码器来进行序列化/反序列化。

例如,

< rect id="Camera_Body" >

<强>输出:

import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._

object CirceSubtypesSerialisers {

  def main(args: Array[String]): Unit = {

    sealed trait Data

    case class OptionsData(data: Seq[String]) extends Data
    case class TextData(data: String) extends Data

    object Data {
      implicit val decodeData: Decoder[Data] = Decoder[OptionsData].map[Data](identity).or(Decoder[TextData].map[Data](identity))

      implicit val encodeData: Encoder[Data] = Encoder.instance {
        case options @ OptionsData(_) => options.asJson
        case text @ TextData(_) => text.asJson
      }
    }

    val optionsJson ="""{ "data": ["option1", "option2"] }""".stripMargin

    decode[Data](optionsJson) match {
      case Right(r: OptionsData) => println(r)
      case Left(l) => println(l)
    }


    val textJson ="""{ "data": "hey, how can i help ya?" }""".stripMargin

    decode[Data](textJson) match {
      case Right(r: TextData) => println(r)
      case Left(l) => println(l)
    }

  }

}

https://circe.github.io/circe/codec.html#warnings-and-known-issuesJsonCodec for sealed traits requires an explicit object definition

中也提到了这一点

答案 1 :(得分:1)

你可以使用circe-generic并为你的jsons添加类型标记:

在你的build.sbt:

libraryDependencies ++= Seq(
  "io.circe" %% "circe-core" % "0.9.3",
  "io.circe" %% "circe-generic" % "0.9.3",
  "io.circe" %% "circe-parser" % "0.9.3"
)

现在让我们定义我们的类并序列化和反序列化它们:

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

import io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
val thing: Thing = SomeThing()


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

   }
}
*/


// deserialize json to Thing
val errorOrMyTrait: Either[io.circe.Error, Thing] = for {
  json <- parse(jsString) // either ADT, since this may not be a legal json
  myDecodedClass <- json.as[Thing] // ADT, since this may be a json that is not in Thing Format
} yield myDecodedClass

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

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

答案 2 :(得分:-1)

您可能会遇到this known issue

根据那里的讨论,也许你可以试试:

import io.circe.generic.JsonCodec

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

object Thing