Reputation: 4231
I am trying to produce 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 ?
Upvotes: 0
Views: 449
Reputation: 6237
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. 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. But how can the type-system know that you can (de-)serialise a generic 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. In the end you will need to write a custom serialiser for the Bar
trait. 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 ???
.
Upvotes: 1