spray-json and list marshalling

不打扰是莪最后的温柔 提交于 2019-12-03 12:17:05

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

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

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.

4lex1v

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