如何使用JSON Spray的HashMap字段在Akka HTTP中支持编组和解组?

时间:2018-10-24 15:46:19

标签: scala akka-http spray-json

我有以下案例类:

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])

编组定义:

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)

但是我仍然遇到这些编译错误:

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]                                                           ^

如果删除前两个隐式对象,则会出现其他编译错误。 如何在Scala中为地图类型定义隐式JSON格式?

1 个答案:

答案 0 :(得分:1)

您只需要编写自定义RootJsonFormat[scala.collection.immutable.HashMap[Id,GuiApplication]]并将其添加到路线范围:

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]  = ???
}