Scala play api for JSON - getting Array of some case class from stringified JSON?

523 views Asked by At

From our code, we call some service and get back stringified JSON as a result. The stringified JSON is of an array of "SomeItem", which just has four fields in it - 3 Longs and 1 String

Ex:

[
{"id":33,"count":40000,"someOtherCount":0,"someString":"stuffHere"},
{"id":35,"count":23000,"someOtherCount":0,"someString":"blah"},
...
]

I've been using the play API to read values out using implicit Writes / Reads. But I'm having trouble getting it to work for Arrays.

For example, I've been try to parse the value out of the response, and then convert it to the SomeItem case class array, but it's failing:

val sanityCheckValue: JsValue: Json.parse(response.body) 
val Array[SomeItem] = Json.fromJson(sanityCheckValue)

I have

implicit val someItemReads = Json.reads[SomeItem]

But it looks like it's not working. I've tried to set up a Json.reads[Array[SomeItem]] as well, but no luck.

Should this be working? Any tips on how to get this to work?

1

There are 1 answers

0
Mario Galic On BEST ANSWER
import play.api.libs.json._

case class SomeItem(id: Long, count: Long, someOtherCount: Long, someString: String)

object SomeItem {
  implicit val format = Json.format[SomeItem]
}

object PlayJson {
  def main(args: Array[String]): Unit = {

    val strJson =
    """
      |[
      |  {"id":33,"count":40000,"someOtherCount":0,"someString":"stuffHere"},
      |  {"id":35,"count":23000,"someOtherCount":0,"someString":"blah"}
      |]
    """.stripMargin

    val listOfSomeItems: Array[SomeItem] = Json.parse(strJson).as[Array[SomeItem]]

    listOfSomeItems.foreach(println)

  }

}