2013-07-18 43 views
10

我使用spray-json將自定義對象列表編組爲JSON。我有以下案例類和它的JsonProtocol。spray-json和list marshalling

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噴霧1.1-M7和噴霧JSON 1.2.5

+0

請參閱[本示例](https://github.com/spray/spray/blob/master/examples/spray-client/simple-spray-client/src/main/scala/spray/examples/Main.scala ),它使用'''List'''。 – opyate

回答

2

您還需要導入你的路由範圍定義的格式:

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

我有那個導入。編組ElementResponse類型的對象工作正常。不起作用的是編組這些對象的列表。 –

3

的要做到這一點最簡單的方法,是從你的列表中進行字符串或你必須處理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 
    } 
} 
+0

這是一個不錯的主意,但我應該如何在我的json協議中使用marshaller? (在我的情況下JollyJsonProtocol) - 將這種隱式方法添加到協議類沒有幫助。 –

+1

我會建議您重命名您的JollyJsonProtocol,並將其作爲[import tax] [2]的伴侶對象。列表編組應該通過將其導入範圍來工作。至於'Stream',只需在列表中調用'toStream'即可 – 4lex1v

5

這是一個老問題,但我想給我的2c。今天看到類似的問題。

Marcin,似乎你的問題沒有真正解決(據我所知) - 你爲什麼接受一個答案?

您是否試過在地方添加import spray.json.DefaultJsonProtocol._?那些負責製造東西,如Seq s,Map s,Option s和Tuple s工作。我會認爲這可能是你的問題的原因,因爲它是List沒有得到轉換。