2014-02-28 73 views
3

我正在使用spray,我需要通過方法返回一個json對象。使用spray.json獲取Json對象

val route = 

path("all-modules") { 
     get { 
      respondWithMediaType(`text/html`) { 
      complete(configViewer.findAllModules.toString) 
      } 
     } 
     } 

這將打印ConfigResults(S1000,Success,List(testDataTypes, mandate, sdp))

但我需要得到這個作爲json對象。我該怎麼做?

我這樣

val route = 

    path("all-modules") { 
     get { 
     respondWithMediaType(`application/json`) { 
      complete{ 
      configViewer.findAllModules 
      } 
     } 
     } 
    } 

嘗試它給出了一個編譯錯誤could not find implicit value for parameter marshaller: spray.httpx.marshalling.ToResponseMarshaller

+0

Btw。你通常不需要使用'respondWithMediaType'指令。編組會自動找出使用哪種內容類型。 – jrudolph

回答

0

你需要告訴噴霧應該如何序列化的情況下類。

只是配置類似

object JsonSupport { 
    implicit val formatConfigResults = jsonFormat3(ConfigResults) 
} 

在jsonFormat'number」的數字代表委員在你的case類的數量。

然後你只需要導入你的路線,你定義這個隱式的類。

import JsonSupport._ 
+1

如果這是關於spray-json的話,它需要一個'import DefaultJsonProtocol._'和一個額外的'import SprayJsonSupport._'在路由文件中。 – jrudolph