spray-json icon indicating copy to clipboard operation
spray-json copied to clipboard

Inconsistent behavior when deserializing null

Open jdanbrown opened this issue 11 years ago • 3 comments

Over the last few months using spray-json I had learned the following (incorrect) rule:

null is allowed iff your type is of the form Option[X]

Today I unlearned this rule when I converted a null into Double.NaN (#8) instead triggering an exception, which is what I was expecting to happen. Trying out a bunch of standard formats, I observe these behaviors when deserializing from null:

JsNull.convertTo[Boolean]          -> error
JsNull.convertTo[Int]              -> error
JsNull.convertTo[Long]             -> error
JsNull.convertTo[Char]             -> error
JsNull.convertTo[String]           -> error
JsNull.convertTo[Seq[Int]]         -> error
JsNull.convertTo[Map[String, Int]] -> error
JsNull.convertTo[(Int, String)]    -> error

JsNull.convertTo[Float]            -> Float.NaN
JsNull.convertTo[Double]           -> Double.NaN
JsNull.convertTo[Unit]             -> ()

JsNull.convertTo[Option[Int]]      -> None

I think the library's behavior would be less surprising and thus easier to use if the rule above did hold. To that end, I propose:

  • Exposing an option for null <-> Float.NaN/Double.Nan, disabled by default
  • Rejecting null -> () for Unit

Thoughts? Are there more cases that I'm missing? Is the issue more subtle than this?

jdanbrown avatar Mar 27 '13 20:03 jdanbrown

Dan, thanks for this analysis. You definitely have a point here. I think we should disallow null for anything but Options. We'll discuss it on our side and come up with a solution. Thanks again for taking the time to analyse and report!

sirthias avatar Mar 28 '13 08:03 sirthias

Any updates on this?

lwei-mdsol avatar Aug 18 '16 15:08 lwei-mdsol

Also, Some(Double.NaN).toJson.convertTo[Option[Double]] yields None.

kaarelnu avatar Feb 16 '17 13:02 kaarelnu