Search code examples
scalaakka-httpspray-json

How to support marshalling and unmarshalling in Akka HTTP with JSON Spray for HashMap fields?


I have the following case classes:

import scala.collection.immutable.HashMap
final case class GuiApplication(testSuites: TestSuites)
final case class GuiApplications(var applications: HashMap[Id, GuiApplication])
final case class Id(val id: Long)
final case class TestSuite()
final case class TestSuites(var testSuites: HashMap[Id, TestSuite])

The marshalling defines:

implicit val applicationsMapFormat = jsonFormat0(HashMap[Id, GuiApplication])
implicit val testsuitesMapFormat = jsonFormat0(HashMap[Id, TestSuite])
implicit val idFormat = jsonFormat1(Id)
implicit val testSuiteFormat = jsonFormat0(TestSuite)
implicit val testSuitesFormat = jsonFormat1(TestSuites)
implicit val applicationFormat = jsonFormat1(GuiApplication)
implicit val applicationsFormat = jsonFormat1(GuiApplications)

But I still get these compile errors:

type mismatch;
[error]  found   : Seq[(Id, GuiApplication)] => scala.collection.immutable.HashMap[Id,GuiApplication]
[error]  required: () => ?
[error]  Note: implicit value applicationsMapFormat is not applicable here because it comes after the application point and it lacks an explicit result type
[error]   implicit val applicationsMapFormat = jsonFormat0(HashMap[Id, GuiApplication])
[error]                                                           ^

If I remove the first two implicits I get other compile errors. How can I define implicit JSON formats for map types in Scala?


Solution

  • You just need to write your custom RootJsonFormat[scala.collection.immutable.HashMap[Id,GuiApplication]] and add it to the scope of your routes:

    implicit val hashMapFormat: RootJsonFormat[scala.collection.immutable.HashMap[Id,GuiApplication]] = new RootJsonFormat[scala.collection.immutable.HashMap[Id,GuiApplication]] {
      override def write(obj: scala.collection.immutable.HashMap[Long, String]): JsValue = ???
      override def read(json: JsValue): scala.collection.immutable.HashMap[Id,GuiApplication]  = ???
    }