问题
I have a a variable
var movieArray = movieText.parseJson
which is of class
println(movieArray.getClass)
class spray.json.JsArray
How do I convert it to a Sequence of case classes e.g
case class Movie(id: Int, title: String)
I tried
1. movieArray.convertTo[Seq[Movie]]
2. movieArray.map(_.convertTo[Movie])
3. for (i <- movieArray) println(i)
gives errors...
1. Cannot find JsonReader or JsonFormat type class for Seq[Movie]
2. value map is not a member of spray.json.JsValue
3. value foreach is not a member of spray.json.JsValue
Any suggestions? Help appreciated.
Correct answer https://github.com/spray/spray-json/issues/259
import spray.json._
import DefaultJsonProtocol._
var movieArray = movieText.stripMargin.parseJson
case class Movie(id: Int, title: String)
implicit val movieFormat = jsonFormat2(Movie)
movieArray.convertTo[Seq[Movie]]
回答1:
Each element of movieArray will have to be converted to an object of type Movie.
movieArray.map(_.convertTo[Movie])
Of course, the above statement depends on availability of logic to convert from Json to instance of Movie (JsonProtocol). Please refer the following for example
https://github.com/spray/spray-json#providing-jsonformats-for-case-classes
来源:https://stackoverflow.com/questions/50319629/how-to-convert-a-jsarray-to-sequence-of-case-classes-with-spray-json