spray-json和列表编组

10

我正在使用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]]

也许你知道问题所在?

我正在使用Scala 2.10.1版本,搭配spray 1.1-M7和spray-json 1.2.5。


请查看此示例,使用了一个List。示例链接在此:https://github.com/spray/spray/blob/master/examples/spray-client/simple-spray-client/src/main/scala/spray/examples/Main.scala - opyate
3个回答

5

这是一个老问题,但我觉得我可以提供我的意见。今天看到了类似的问题。

Marcin,看起来你的问题并没有被解决(就我所知)- 为什么你要接受一个答案?

你尝试在哪些地方添加import spray.json.DefaultJsonProtocol._了吗? 这些代码负责使SeqMapOptionTuple等内容正常工作。 我认为这可能是你的问题的原因,因为没有将List转换。


3

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

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],让spray分块来处理。
get {
  complete {
    List(new ElementResponse(...), new ElementResponse(...)).toStream
  }
}

这是一个不错的想法,但我应该如何在我的JSON协议中使用marshaller呢?(在我的情况下是JollyJsonProtocol)- 将此隐式方法添加到协议类并没有帮助。 - Marcin Cylke
1
我建议您将JollyJsonProtocol重命名并将其作为[import tax][2]的伴生对象。通过将其导入到作用域中,列表marshaller应该能够正常工作。至于“Stream”,只需在列表上调用“toStream”即可。 - 4lex1v

2
你还需要在路由范围内导入你定义的格式:
import JollyJsonProtocol._
get {
      complete {
        List(new ElementResponse(...), new ElementResponse(...))
      }
    }

4
我已经导入了那个。将类型为ElementResponse的对象编组运行良好。不起作用的是对这些对象列表进行编组。 - Marcin Cylke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接