Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSArray object into a list of objects in Scala Play

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.

like image 774
jcm Avatar asked Mar 18 '23 19:03

jcm


1 Answers

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))
like image 75
acjay Avatar answered Mar 21 '23 18:03

acjay