【问题标题】:spray-json and list marshallingSpray-json 和列表编组
【发布时间】:2013-07-18 01:15:39
【问题描述】:

我正在使用 spray-json 将自定义对象列表编组为 JSON。我有以下案例类及其 JsonProtocol。

case class ElementResponse(name: String, symbol: String, code: String, pkwiu: String, remarks: String, priceNetto: BigDecimal, priceBrutto: BigDecimal, vat: Int, minInStock:Int,                        maxInStock: Int)

object JollyJsonProtocol extends DefaultJsonProtocol with SprayJsonSupport  {
 implicit val elementFormat = jsonFormat10(ElementResponse)
}

当我尝试加入这样的路线时:

get {
      complete {
        List(new ElementResponse(...), new ElementResponse(...))
      }
    }

我收到一条错误消息:

 could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[List[pl.ftang.scala.polka.rest.ElementResponse]]

也许你知道问题出在哪里?

我正在使用带有 spray 1.1-M7 和 spray-json 1.2.5 的 Scala 2.10.1

【问题讨论】:

标签: scala scala-2.10 spray spray-json


【解决方案1】:

这是一个老问题,但我想给我的 2c。今天也在研究类似的问题。

Marcin,您的问题似乎并没有真正解决(据我所知)-您为什么接受一个答案?

您是否尝试在某些地方添加import spray.json.DefaultJsonProtocol._?那些负责使Seqs、Maps、Options 和Tuples 等工作正常工作。我认为这可能是您的问题的原因,因为它是 List 没有得到转换。

【讨论】:

    【解决方案2】:

    最简单的方法是从您的列表中创建一个字符串,否则您将不得不处理 ChunckedMessages:

    implicit def ListMarshaller[T](implicit m: Marshaller[T]) =
        Marshaller[List[T]]{ (value, ctx) =>
          value match {
            case Nil => ctx.marshalTo(EmptyEntity)
            case v => v.map(m(_, ctx)).mkString(",")
          }
        }
    

    秒的方法是将你的列表转换成Stream[ElementResponse],让chunck为你喷。

    get {
      complete {
        List(new ElementResponse(...), new ElementResponse(...)).toStream
      }
    }
    

    【讨论】:

    • 这是个好主意,但是我应该如何在我的 json 协议中使用 marshaller? (在我的例子中是 JollyJsonProtocol) - 将此隐式方法添加到协议类没有帮助。
    • 我建议您重命名您的 JollyJsonProtocol 并将其作为 [import tax][2] 的伴随对象。列表编组器应该通过将其导入范围来工作。至于Stream,请在您的列表中拨打toStream
    【解决方案3】:

    你还需要导入你在路由范围上定义的格式:

    import JollyJsonProtocol._
    get {
          complete {
            List(new ElementResponse(...), new ElementResponse(...))
          }
        }
    

    【讨论】:

    • 我有那个导入。编组 ElementResponse 类型的对象可以正常工作。不起作用的是编组这些对象的列表。
    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 2015-07-26
    • 2013-12-29
    • 2016-07-22
    • 2019-03-08
    • 1970-01-01
    • 2015-09-26
    • 2021-11-22
    相关资源
    最近更新 更多