Circe - 如何为额外类型指定编码器?

时间:2018-04-30 20:38:09

标签: scala circe

我对此处给出的示例做了一个简单的修改:https://circe.github.io/circe/,添加了类型Basics。为什么不运行?

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


class Basics(Name:String,Cached:Boolean)

sealed trait Foo
case class Bar(basics:Basics,xs: Vector[String]) extends Foo
case class Qux(basics:Basics,i: Int, d: Option[Double]) extends Foo

val foo: List[Foo] = List(Qux(new Basics("Cat",true),13, Some(14.0)),Bar(new Basics("Cat",true),Vector("cat")))
val json = foo.asJson.noSpaces
println(json)

val decodedFoo = decode[List[Foo]](json)
println(decodedFoo)

我特意得到:

ScalaFiddle.scala:11: error: could not find implicit value for parameter encoder: circe.this.Encoder[List[ScalaFiddle.this.Foo]]
val json = foo.asJson.noSpaces
               ^
ScalaFiddle.scala:11: error: not enough arguments for method asJson: (implicit  encoder: circe.this.Encoder[List[ScalaFiddle.this.Foo]])circe.this.Json.
Unspecified value parameter encoder.
val json = foo.asJson.noSpaces
               ^
ScalaFiddle.scala:14: error: could not find implicit value for evidence parameter of type circe.this.Decoder[List[ScalaFiddle.this.Foo]]
val decodedFoo = decode[List[Foo]](json)

额外魔法:

sealed trait Bat
case class Basics(name:String,cached:Boolean) extends Bat

修复它。为什么呢?

同样

 case class Basics(name:String,cached:Boolean)

1 个答案:

答案 0 :(得分:1)

Basics需要case class来自动导出解码器。

Circe基于无形无法进行自动推导,无形无关于案例类,而不是普通类。

作为Scala的经验法则,如果您的类代表某种记录/数据,则使用用例类。