Spray-Json: serialize None as null

夙愿已清 提交于 2020-12-12 10:13:46

问题


I am porting a rest API to scala, using akka-http with spray-json.

The old API had the following response:

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

Now I want to maintain exact backwards compatibility, so when there's no error I want an error key with a null value.

However I can't see any support for this in spray-json. When I serialize the following with a None error:

case class Response(result: Result, error: Option[Error])

I end up with

{
    "result": { ... }
}

And it completely drops the error value


回答1:


NullOption trait should serialise nulls

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.

for example

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}


来源:https://stackoverflow.com/questions/60759838/spray-json-serialize-none-as-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!