0

I'm completely new to Scala and Play and i stumbled upon the following the problem:

Given the following JSON structure:

[
  {
    "name": "Adam",
    "age": 19
  },
  {
    "name": "Berta",
    "age": 22
  },
...
]

I would like to map this JSON to a case classes like this:

case class User(name: String, age: Int)
case class Users(users: Seq[User])

or at least something like Seq[User].

I don't know how to traverse the JsPath because there is no key.

I tried to define an implicit read but either he cannot resolve the symbol "read" or he cannot found an implicit for user.

object User {
  implicit val reads: Reads[User] = Json.reads[User]
}
object Users {
  implicit val usersReads: Reads[Users] = (
    (JsPath).read[Seq[User]]
  )(Users.apply _)
}

How can I map my JSON to a working model?

1 Answer 1

3

Something like this will work

import play.api.libs.json._

case class User(name: String, age: Int)
case class Users(users: Seq[User])

object User {
  implicit val reads = Json.reads[User]
}

object Users {
  implicit val reads: Reads[Users] = Reads {
      _.validate[Seq[User]].map(Users(_))
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It works but my IntelliJ told my that no implicits could be found for Seq[User]..however could you shortly explain what the map part does? Thx!
You don't even need the second implicit object. Json.parse(s).as[Seq[User]] works just fine too.
its just .map(users => Users(users))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.