How to convert a JsArray to sequence of case classes with spray-json?

旧城冷巷雨未停 提交于 2019-12-13 16:42:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!