How setup spray-json to set null when json element is not present?
The only way I can think of is to implement your own Protocol via read/write
, which might be cumbersome. Below is a simplified example. Note that I changed the age
to be an Integer
instead of an Int
since Int
is an AnyVal
, which is not nullable by default. Furthermore, I only consider the age
field to be nullable, so you might need to adopt as necessary. Hope it helps.
case class Foo (name:String, age: Integer) object MyJsonProtocol extends DefaultJsonProtocol { implicit object FooJsonFormat extends RootJsonFormat[Foo] { def write(foo: Foo) = JsObject("name" -> JsString(foo.name), "age" -> Option(foo.age).map(JsNumber(_)).getOrElse(JsNull)) def read(value: JsValue) = value match { case JsObject(fields) => val ageOpt: Option[Integer] = fields.get("age").map(_.toString().toInt) // implicit conversion from Int to Integer val age: Integer = ageOpt.orNull[Integer] Foo(fields.get("name").get.toString(), age) case _ => deserializationError("Foo expected") } } } import MyJsonProtocol._ import spray.json._ val json = """{ "name": "Meh" }""".parseJson println(json.convertTo[Foo]) // prints Foo("Meh",null)
It seems you're out of luck
From the doc you linked:
spray-json will always read missing optional members as well as
null
optional members asNone
You can customize the json writing, but not the reading.