Scala - 用于案例类的自定义Marshaller

时间:2015-09-02 18:32:06

标签: json scala marshalling spray

我正在为Spray框架实现REST api并尝试以漂亮的json格式实现响应

这里有一点代码:

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")
        }
      )
    }
  }
}

请注意,case类在构造函数中可能缺少值,例如“Response”类“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

请举例说明我的案例?

1 个答案:

答案 0 :(得分:1)

如果您想更改json中字段的顺序,只需更改案例类中的顺序。

如果您不想显示空或空的字段,只需使用默认值为None的选项,默认情况下,spray-json不会序列化为None的字段,因此它们不会显示在json中。

case class ErrorResponse(APIv: Option[String] = None, error: Error, requestNr: Option[String] = None)