spray-json and list marshalling

爱⌒轻易说出口 提交于 2019-12-04 18:17:27

问题


I'm using spray-json to marshal lists of custom objects into JSON. I have the following case class and its 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)
}

When I try to put in in a route like this one:

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

I get an error saying that:

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

Perhaps you know what is the problem?

I'm using Scala 2.10.1 with spray 1.1-M7 and spray-json 1.2.5


回答1:


You also need to import the format you defined on the route scope:

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



回答2:


This is an old issue, but I feel like giving my 2c. Was looking at similar issues today.

Marcin, it seems your issue was not actually solved (as far as I can read) - why did you accept one answer?

Did you try adding import spray.json.DefaultJsonProtocol._ in places? Those are in charge of making things such as Seqs, Maps, Options and Tuples to work. I would assume this might be the cause of your problem, since it's the List that is not getting converted.




回答3:


The easiest way to do this, is to make a String from your list or you'll have to deal with 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(",")
      }
    }

The seconds way is to convert your list into the Stream[ElementResponse] and let spray chunck it for you.

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


来源:https://stackoverflow.com/questions/17734457/spray-json-and-list-marshalling

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