【问题标题】:How to convert a JsArray to sequence of case classes with spray-json?如何使用 spray-json 将 JsArray 转换为案例类序列?
【发布时间】:2018-10-23 11:35:16
【问题描述】:

我有一个变量

var movieArray = movieText.parseJson

属于哪一类

println(movieArray.getClass)
class spray.json.JsArray

如何将其转换为案例类序列,例如

case class Movie(id: Int, title: String)

我试过了

1. movieArray.convertTo[Seq[Movie]]
2. movieArray.map(_.convertTo[Movie])
3. for (i <- movieArray) println(i)

给出错误...

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

有什么建议吗?帮助表示赞赏。

正确答案 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]]

【问题讨论】:

    标签: scala spray-json


    【解决方案1】:

    movieArray 的每个元素都必须转换为 Movie 类型的对象。

    movieArray.map(_.convertTo[Movie])
    

    当然,上述语句取决于从 Json 转换为 Movie 实例 (JsonProtocol) 的逻辑的可用性。请参考以下示例

    https://github.com/spray/spray-json#providing-jsonformats-for-case-classes

    【讨论】:

    • 使用 map 时出现以下错误:“value map is not a member of spray.json.JsValue”。也就是说JsArray没有map函数?
    • 同样for (i &lt;- movieArray) println(i) 导致错误value foreach is not a member of spray.json.JsValue
    • .map 在 JsArray 上可用,而不是在 JsValue 上。试试这个JsArray(movieArray)
    • 步骤:到 AST var movieArray = movieText.parseJson 打印类println(movieArray.getClass) 打印... class spray.json.JsArray 映射到电影案例类movieArray = movieArray.map(_.convertTo[Movie]) 给出错误value map is not a member of spray.json.JsValue
    • 我的错。我在没有完全理解你的问题的情况下做出了回应。只要相应的 JsonProtocol(用于从/到 json 的转换)在范围内可用,movieArray.convertTo[Seq[Movie]] 就应该工作。这可以通过在执行转换语句之前导入 JsonProtocol 来完成。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2014-09-02
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多