6

I have the following JSON:

[{"id_str":"67979542","name":"account"}, {"id_str":"12345678","name":"account2"}, {"id_str":"3423423423","name":"account3"}]

which has been parsed into a play.api.libs.json.JsArray object with 3 elements.

I want to parse this JsArray into my a custom object Group with the following code:

 case class Group(id: String, name: String)

  implicit val twitterGroupReads: Reads[Group] = (
    (JsPath \\ "id_str").read[String] and
    (JsPath \\ "name").read[String]
    )(Group.apply _)

But I don't know how to use the library to get all the elements from the array and parse those into my custom object.

1 Answer 1

8

The Play JSON framework has a number of built-in objects for handling JSON, among which is Reads.traversableReads, which will be used implicitly to deserialize collections of other types for which a Reads object can be found implicitly. And you wrote a proper Reads object. So unless I'm missing something, you're good to go:

scala> import play.api.libs.json._
import play.api.libs.json._

scala> import play.api.libs.functional.syntax._
import play.api.libs.functional.syntax._

scala> case class Group(id: String, name: String)
defined class Group

scala> implicit val twitterGroupReads: Reads[Group] = (
     |     (JsPath \\ "id_str").read[String] and
     |     (JsPath \\ "name").read[String]
     |     )(Group.apply _)
twitterGroupReads: play.api.libs.json.Reads[Group] = play.api.libs.json.Reads$$anon$8@f2fae02

scala> val json = Json.parse("""[{"id_str":"67979542","name":"account"}, {"id_str":"12345678","name":"account2"}, {"id_str":"3423423423","name":"account3"}]""")
json: play.api.libs.json.JsValue = [{"id_str":"67979542","name":"account"},{"id_str":"12345678","name":"account2"},{"id_str":"3423423423","name":"account3"}]

scala> json.as[Seq[Group]]
res0: Seq[Group] = List(Group(67979542,account), Group(12345678,account2), Group(3423423423,account3))
Sign up to request clarification or add additional context in comments.

1 Comment

One thing to add: if you’re fine with using exact same field names in JSON and your Scala classes, then a custom Reads implementation is not necessary, and your JSON conversion code becomes very simple: implicit val reads = Json.reads[Group]. Example: stackoverflow.com/a/34618829/56285

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.