Serialization of None Incorrect When In Case Class
Closed this issue · 3 comments
lambdaknight commented
case class Foo(a: Option[String])
val json = generate(Foo(None))
In this code json is set to {}
rather than {"a":null}
.
It should be as simple as adding this code to CaseClassSerializer.scala:32:
else {
json.writeFieldName(methodOpt.map {_.getName}.getOrElse(field.getName))
provider.getNullValueSerializer.serialize(null, json, provider)
}
lambdaknight commented
Is that the canonical way of serializing Option[_]? It seems like it would violate the principle of least surprise to have a None show up as just not being there.
codahale commented
There is no canonical way of serializing Scala types to JSON values. This is one of many.
As far as things being surprising, mapping a trinary value ("blah"
, null
, or a field which doesn't exist) to a binary value (Some("blah")
, None
) will always involve collision and thus "surprise."