Play Json serialize/deserialize mutual recursive

佐手、 提交于 2019-12-13 22:25:02

问题


How to serialize and deserialize these structures using Play Json combinators?

final case class WriteGroupEntity(label: String, items: Map[String, WriteEntity])
final case class WriteEntity(label: String,
                             propertyType: String,
                             groups: Option[Map[String, WriteGroupEntity]])

回答1:


Two days are gone and I've finally found a solution.

import play.api.libs.json._
import play.api.libs.functional.syntax._

final case class GroupEntity(label: String, items: Map[String, Entity])
final case class Entity(label: String,
                        propertyType: String,
                        groups: Option[Map[String, GroupEntity]])

implicit lazy val ge: OWrites[GroupEntity] = (
  (JsPath \ "label").write[String] and
    (JsPath \ "items").lazyWrite(Writes.map[Entity](e))
)(unlift(GroupEntity.unapply))

implicit val e: OWrites[Entity] = Json.writes[Entity]

implicit lazy val ger: Reads[GroupEntity] = (
  (JsPath \ "label").read[String] and
    (JsPath \ "items").lazyRead(Reads.map[Entity](er))
)(GroupEntity)

implicit val er = Json.reads[Entity]


来源:https://stackoverflow.com/questions/55255292/play-json-serialize-deserialize-mutual-recursive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!