codahale/jerkson

Serialization of None Incorrect When In Case Class

Closed this issue · 3 comments

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

Fight it out with @tc: #6

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.

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."