我執行REST API的噴霧框架,努力實現好的JSON格式斯卡拉 - 定製的Marshaller的情況下,類
這裏的反應是有點如果代碼:
case class Response(msg: String, APIv: String = "", requestNr: String = "")
case class Error(msg: String, errNo: String, exception: String = "")
case class ErrorResponse(error: Error, APIv: String = "", requestNr: String = "")
object Marshallers extends DefaultJsonProtocol with SprayJsonSupport {
implicit val response = jsonFormat3(Response)
implicit val error = jsonFormat3(Error)
implicit val errorResponse = jsonFormat3(ErrorResponse)
}
那麼對於get方法我使用它這樣:
def getRoute = get {
path("schema"/Segment) { schemaClassShortId : String =>
respondWithMediaType(`application/json`) {
complete(
FakeStorage.service.getSchema(schemaClassShortId) match {
case None => new ErrorResponse(new Error("SchemaClass with ID: ["+schemaClassShortId + "] not found", EC.SchemaClassNotFound))
case Some(schema) => new Response(schema.toString, "APIv-test", "RequestNr-test")
}
)
}
}
}
注意這種情況下,類可以在構造函數中遺漏值例如像對「響應」類「APIV」或「RequestNr」可能是未通過,並設置爲空 - ( 「」)
這種類會產生休耕JSON響應:
{
"error": {
"msg": "SchemaClass with ID: [wrongId] not found",
"errNo": "1000",
"exception": ""
},
"APIv": "",
"requestNr": ""
}
但是我想改變兩兩件事:
1)令
{
"APIv": "",
"error": {
"msg": "SchemaClass with ID: [wrongId] not found",
"errNo": "1000",
"exception": ""
},
"requestNr": ""
}
2)不包含空物體成爲響應
{
"error": {
"msg": "SchemaClass with ID: [wrongId] not found",
"errNo": "1000"
}
}
據我所知,我需要編寫自定義Marshaller - 但我不知道如何做到這一點作爲即時通訊非常新的噴霧和特別斯卡拉
你能請示例我的情況?
檢查此頁面https://github.com/spray/spray-json#providing-jsonformats-for-other-types – maks