scalaakka-httpspray-json

Spray-Json: serialize None as null


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


Solution

  • 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}