【发布时间】:2015-11-28 09:42:18
【问题描述】:
我正在为 Spray 框架实现 REST api,并尝试以漂亮的 json 格式实现响应
这里有一点if代码:
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 - 但是我不知道该怎么做,因为我对 Spray 和特别是 Scala 很陌生
你能举出我的例子吗?
【问题讨论】:
-
查看此页面github.com/spray/…
标签: json scala marshalling spray