[英]serializing polymorphic classes using spray.json getting could not find implicit value for evidence parameter of type
I am trying to produce json 我正在尝试产生json
trait Bar
case class Foo(name:String) extends Bar
case class Buz(name:String,age:Int) extends Bar
case class Responsive(id:String ,bars:List[Bar])
when calling 打电话时
import spray.json._
val foo = Foo("foo")
val fooRes = Responsive("abc",List(foo))
println(fooRes.toJson)
I am getting 我正进入(状态
Cannot find JsonWriter or JsonFormat type class for com.demo.Responsive
println(s" res = ${fooRes.toJson}")
^
when I add 当我添加
implicit val impResponsive = jsonFormat2(Responsive)
I am getting 我正进入(状态
`could not find implicit value for evidence parameter of type` com.demo.routing.JsonImplicits.JF[List[com.avi.demo.Bar]]
implicit val impResponsive = jsonFormat2(Responsive)
^
why am I getting these errors ? 为什么会出现这些错误? how can I solve it ?
我该如何解决?
The error you get on Responsive
is really due to the fact that this class contains a reference to Bar
and to the fact you don't have a (de-)serialiser for the Bar
trait. 您在
Responsive
上遇到的错误实际上是由于此类包含对Bar
的引用,以及您没有Bar
特性的(反)序列化器。 More in detail, the type-system knows that you can (de-)serialise instances of Foo
, Buz
and Responsive
because you have the appropriate formats in scope. 更详细地讲,类型系统知道您可以对
Foo
, Buz
和Responsive
实例进行反序列化,因为您在范围内具有适当的格式。 But how can the type-system know that you can (de-)serialise a generic Bar
? 但是类型系统如何知道您可以对通用
Bar
进行(反)序列化?
It would be great if spray-json could support this use case making the Bar
trait sealed and defining the serialisers for its children, but I am afraid that this wouldn't work either. 如果Spray-json能支持此用例,使
Bar
特性密封并为其子级定义序列化程序,那就太好了,但是我担心这也不行。 In the end you will need to write a custom serialiser for the Bar
trait. 最后,您将需要为
Bar
特性编写一个自定义序列化程序。 If you want a proof that the error is due to this just add the following to your implicit formats: 如果您想证明错误是由于此导致的,只需将以下内容添加到隐式格式中:
implicit val barFormat: RootJsonFormat[Bar] = ???
Everything should compile now, but obviously fail at runtime due to the ???
现在一切都应该编译了,但是显然由于
???
而在运行时失败了 . 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.