-1

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]])
Chaitanya
  • 3,590
  • 14
  • 33
kapranov.anton
  • 423
  • 5
  • 14

1 Answers1

0

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]
E_net4
  • 27,810
  • 13
  • 101
  • 139
kapranov.anton
  • 423
  • 5
  • 14
  • This is good but I in development this is not safe. You can't track down the error while `Reading` or `Writing`. – Rex Mar 20 '19 at 13:56
  • just a suggestion, you need to create your own `reads and writes` for safer validation. – Rex Mar 20 '19 at 13:59