问题
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 customJsonProtocol
you can enforce the rendering of undefined members asnull
.
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