2014-02-28 70 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