Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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]])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
290 views
Welcome To Ask or Share your Answers For Others

1 Answer

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...