Question

I'm working with Play 2.2.x

I want to map a flat json object to a hierarchical object structure using Format. Here's an example.

case class Hobby(id: String, name: String)
case class PersonWithHobby(id: String, name: String, hobby: Hobby)

But my json is is a flat structure

{"id":"123, "name":"Joe", hobbyId:"abc", "hobbyName":"programming"}

I'm trying to figure out how to do this;

val personFormat = (
    (__ \ "id").format[String] and
    (__ \ "name").format[String] and
    ((__ \ "id").json.pick[String] and 
     (__ \ "name").json.pick[String]).format[Hobby]
)

Of course, the code above it doesn't work. It's just trying to show what I want to do.

Was it helpful?

Solution

Here's a good way to define the format (combining a few concepts from ScalaJsonCombinators):

val personFormat: Format[PersonWithHobby] = (
(__ \ "id").format[String] and
(__ \ "name").format[String] and
  (
    (__ \ "hobbyId").format[String] and
    (__ \ "hobbyName").format[String]
  )(Hobby.apply, unlift(Hobby.unapply))
)(PersonWithHobby.apply, unlift(PersonWithHobby.unapply))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top