我正在将 REST API 移植到 scala,使用 akka-http 和 Spray-json。
旧 API 有以下响应:
{
"result": { ... },
"error": null
}
现在我想保持精确的向后兼容性,因此当没有错误时我需要一个带有 null
值的 error
键。
但是我在 Spray-json 中看不到对此的任何支持。当我序列化以下内容时出现 None
错误:
case class Response(result: Result, error: Option[Error])
我最终得到
{
"result": { ... }
}
并且它完全降低了错误值
最佳答案
NullOption
特征应该序列化空值
The
NullOptions
trait supplies an alternative rendering mode for optional case class members. Normally optional members that are undefined (None
) are not rendered at all. By mixing in this trait into your customJsonProtocol
you can enforce the rendering of undefined members asnull
.
例如
import spray.json._
case class Response(result: Int, error: Option[String])
object ResponseProtocol extends DefaultJsonProtocol with NullOptions {
implicit val responseFormat = jsonFormat2(Response)
}
import ResponseProtocol._
Response(42, None).toJson
// res0: spray.json.JsValue = {"error":null,"result":42}
关于scala - Spray-Json:将 None 序列化为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60759838/