关于scala:spray-json和列表编组

spray-json and list marshalling

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

1
2
3
4
5
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)
}

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

1
2
3
4
5
get {
      complete {
        List(new ElementResponse(...), new ElementResponse(...))
      }
    }

我收到一条错误消息:

1
 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一起使用


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

Marcin,看来您的问题并未真正解决(据我所读)-为什么您接受一个答案?

您是否尝试在地方添加import spray.json.DefaultJsonProtocol._?这些负责使诸如Seq s,Map s,Option s和Tuple s之类的东西起作用。我认为这可能是导致您出现问题的原因,因为List没有得到转换。


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

1
2
3
4
5
6
7
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],并为您喷雾成块。

1
2
3
4
5
get {
  complete {
    List(new ElementResponse(...), new ElementResponse(...)).toStream
  }
}


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

1
2
3
4
5
6
import JollyJsonProtocol._
get {
      complete {
        List(new ElementResponse(...), new ElementResponse(...))
      }
    }