scala - Spray-Json:将 None 序列化为 null

标签 scala akka-http spray-json

我正在将 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 custom JsonProtocol you can enforce the rendering of undefined members as null.

例如

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/

相关文章:

json - 如何使用 Spark 和 Spray Json 读取 json 文件并转换为案例类

scala - Spark从具有相同名称的所有子文件夹中递归读取文件

scala - 使用数据框模式的 Spark map 数据框

scala - 创建 Spring Data JPA 存储库的 Scala 方法

scala - 猫 : how to find the specific type from implicits

scala - 如何创建一个可以稍后通过方法调用接收元素的 Source?

scala - Akka HTTP 客户端 websocket 意外关闭

scala - 如何在 Akka actor 中等待文件上传流完成

scala - 如何在 Actor 中包装 REST API 客户端

scala - 无法使用 spray-json 反序列化通用集合