jsonscalasprayspray-json

Recursive data types and custom serializers in spray-json


I have a recursive data structure that I want to write a custom spray-json serializer for.

case class Counts(var count: Int, var properties: mutable.Map[String, Counts])

object MyJsonProtocol extends DefaultJsonProtocol {
  import DefaultJsonProtocol._

  implicit object CountsJsonFormat extends RootJsonFormat[Counts] {
    def read(json: JsValue) = ???
    def write(c: Counts) = {
      // Flatten count and properties into the same object.
      val properties = c.properties.toJson.asJsObject
      val fields = properties.fields + ("count" -> JsNumber(c.count))
      JsObject(fields.toSeq: _*)
    }
  }
}

I've seen the documentation for how to do this for a case class if you use the builtin serialization logic, but I have no idea how to apply that to a custom serializer. I get this compiler error:

Cannot find JsonWriter or JsonFormat type class for scala.collection.mutable.Map[String,co.asku.acuity.EventCounter.Counts]
val properties = c.properties.toJson.asJsObject
                              ^

Solution

  • spray-json formats can't handle mutable Maps by default (see this disussion that has happened a while ago on the mailing list). Change the type of properties to be an immutable Map (which I think is better anyways) and your format will work as expected.