spray / spray-json

A lightweight, clean and simple JSON implementation in Scala
Apache License 2.0
972 stars 190 forks source link

spray.json.JsArray to sequence of case classes #259

Closed lehtone1 closed 6 years ago

lehtone1 commented 6 years ago

How do I convert a spray.json.JsArray to sequence of case classes?

e.g. I have a variable

movieArray which is of typespray.json.JsArray and I would like to turn it into a sequence of Movie case classes case class Movie(id: Int, title: String)

I tried already movieArray.convertTo[Seq[Movie]] and movieArray.map(_.convertTo[Movie]), but neither seemed to work.

ktoso commented 6 years ago

Can you define does "not work" mean here? Pasting the compile or runtime errors you encountered would make helping you easier.

This works:

    "works" in {
      case class Movie(id: Int, title: String)

      import spray.json._
      import DefaultJsonProtocol._ // if you don't supply your own Protocol (see below)
      implicit val movieFormat = jsonFormat2(Movie)

      val x = """
        |[
        |  { "id": 12, "title": "that movie" }
        |]
      """.stripMargin.parseJson

      info("it + " + x.convertTo[Seq[Movie]])
    }
lehtone1 commented 6 years ago

"not work" -meant that I got the following errors

Cannot find JsonReader or JsonFormat type class for Seq[Movie] value map is not a member of spray.json.JsValue

Followed your instructions, and now I got an error which says...

Cannot automatically determine case class field names and order for 'Movie', please use the 'jsonFormat' overload with explicit field name specification

Any suggestions for next step?

lehtone1 commented 6 years ago

Apparently I had a problem in my class. Your solution is correct. Thanks

ktoso commented 6 years ago

Happy hakking