Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use nested case classes and spray json implicits

Tags:

json

scala

spray

I am trying to convert case classes to json with spray.io json. The code below:

case class Value(amt: Int)
case class Item(name: String, count: Value)
object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val itemFormat = jsonFormat2(Item)
}
import MyJsonProtocol._
import spray.json._
val json = Item("mary", Value(2)).toJson
println(json)

gives:

could not find implicit value for evidence parameter of type onextent.bluecase.examples.ex1.ExampleJson2.MyJsonProtocol.JF[Value]

I've tried to define a JsonProtocol for Value as well but get same. Searching stackoverflow I only see this error related to generics, which this is not.

What am I missing? (re-reading about implicits now...)

like image 658
navicore Avatar asked Mar 12 '23 03:03

navicore


1 Answers

You need a json format for your Value class as it is part of your Item class. So your object would need to look like this:

object MyJsonProtocol extends DefaultJsonProtocol {
 implicit val valueFormat = jsonFormat1(Value)
 implicit val itemFormat = jsonFormat2(Item)
}
like image 148
StuartMcvean Avatar answered Mar 23 '23 13:03

StuartMcvean