gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:22:51 25 4
gpt4 key购买 nike

我正在使用带有spray-json的akka​​-http将rest API移植到scala。

旧 API 有以下响应:

{
"result": { ... },
"error": null
}

现在我想保持精确的向后兼容性,所以当没有错误时我想要一个 errornull 的 key 值(value)。

但是我在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com