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.

Jonik
  • 80,077
  • 70
  • 264
  • 372
jcm
  • 5,499
  • 11
  • 49
  • 78

1 Answers1

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))
acjay
  • 34,571
  • 6
  • 57
  • 100
  • 3
    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: http://stackoverflow.com/a/34618829/56285 – Jonik Jan 07 '16 at 05:16