2

How do I read multiple json objects from a request and convert them into my own custom object. For example, lets say we are retrieving a list of users with the following json:

{
  "users":[
    {
      "name": "Bob",
      "age": 31.0,
      "email": "[email protected]"
    },
    {
      "name": "Kiki",
      "age":  25.0,
      "email": null
    }
  ]
}

and my case class looks like the following

case class User(firstName: String, age: Double, email: String)

In this case the firstName value is differnt from the "name" json value. How do I get a Seq[User] from the given json file with the different names. I can't find any examples where someone is reading from a json file with multiple objects.

Thanks in advance.

1 Answer 1

5

Play's type class-based JSON library provides reader and writer instances for Seq[A] for any A with the appropriate instances, so all you have to do is provide a reader instance for your user type and you get a reader for a collection of users for free.

We can start with the following case class (note that I've made the fact that the email address is optional explicit with Option):

case class User(firstName: String, age: Double, email: Option[String])

Next we define our reader. I'm using 2.1's combinators, but there are other (more verbose) options.

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

implicit val userReads = (
  (__ \ 'name).read[String] and
  (__ \ 'age).read[Double] and
  (__ \ 'email).read[Option[String]]
)(User.apply _)

We can test it:

val userJson = """{
  "users": [
    { "name": "Bob",  "age": 31.0, "email": "[email protected]" },
    { "name": "Kiki", "age": 25.0, "email": null }
  ]
}"""

val users = (Json.parse(userJson) \ "users").as[Seq[User]]

And then:

scala> users foreach println
User(Bob,31.0,Some([email protected]))
User(Kiki,25.0,None)

As expected.

Sign up to request clarification or add additional context in comments.

Comments

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.