格式化程序没问题,但它们仅适用于案例类。
所以你所要做的就是调整它们:
case class Apple(id:String, name:String)
case class Fruit(id:String,ftype:String)
case class Basket(b:Map[Fruit,Apple])
更新
好的,还有另一个问题。 JSON 有一个限制,即 Map 的 Key 必须是 字符串。
在这里查看我的答案:https://stackoverflow.com/a/53896463/2750966
好的,这里是 Play 的示例:
implicit val formata: Format[Apple] = Json.format
implicit val mapReads: Reads[Map[Fruit, Apple]] = (jv: JsValue) =>
JsSuccess(jv.as[Map[String, Apple]].map { case (k, v) =>
(k.split("::").toList match {
case id :: ftype :: _ => Fruit(id, ftype)
case other => throw new IllegalArgumentException(s"Unexpected Fruit Key $other")
}) -> v
})
implicit val mapWrites: Writes[Map[Fruit, Apple]] = (map: Map[Fruit, Apple]) =>
Json.toJson(map.map { case (fruit, o) =>
s"${fruit.id}::${fruit.ftype}" -> o
})
implicit val jsonMapFormat: Format[Map[Fruit, Apple]] = Format(mapReads, mapWrites)
implicit val formatb: Format[Basket] = Json.format
使用此示例数据可以正常工作:
val basket = Basket(Map(Fruit("12A", "granate") -> Apple("A11", "The Super Apple"),
Fruit("22A", "gala") -> Apple("A21", "The Gala Premium Apple")))
val json = Json.toJson(basket) // >> {"b":{"12A::granate":{"id":"A11","name":"The Super Apple"},"22A::gala":{"id":"A21","name":"The Gala Premium Apple"}}}
json.as[Basket] // >> Basket(Map(Fruit(12A,granate) -> Apple(A11,The Super Apple), Fruit(22A,gala) -> Apple(A21,The Gala Premium Apple)))
这里是Scalafiddle