Add serialization feature: strict numbers
See original GitHub issueThis is a proposal for a new serialization feature, SerializationFeature.STRICT_NUMBERS
.
This feature would be disabled by default. With this feature enabled, the following actions would throw JsonProcessingException
:
- Attempting to serialize
+Infinity
,-Infinity
, orNaN
- Attempting to serialize a
long
that cannot be represented as a numerically-equivalentdouble
+Infinity, -Infinity, NaN
Non-finite numbers cannot be represented in JSON. Jackson’s current behavior is to serialize them as strings. This “works” if Jackson is on both ends (serializing and deserializing) but not necessarily when a different actor is deserializing. In particular, if client-side JavaScript is deserializing, the current behavior masks a class of bugs that might be difficult to detect – putting strings where the client expects numbers.
Checking whether a number is finite is extremely low-cost (Double.isFinite(x)
) so this part of the feature should not have a noticeable performance burden.
Personally, I’m not intentionally serializing non-finite values anywhere and I’d prefer it if Jackson would throw an exception if I did so by mistake.
Longs that don’t fit
Edit: I mistakenly called this a limitation of numbers in JSON, when it’s actually about numbers in JavaScript.
Not all long
values can be represented as 64-bit floating point numbers (double
), which is the only number type in JSONJavaScript. For example, casting these numbers to double
in Java will result in loss of information:
2^63 - 1
2^53 + 1
All long
values whose absolute value is <= 2^53
can be represented exactly as double
, so there is a fast path for validation of most common long
values. This will likely include all values that come from epoch millisecond timestamps or SQL auto-incrementing IDs. Randomly generated long
values, however, would likely require the slow path (if there is a slow path) and be invalid.
All short
and int
values are smaller than 2^53
, so this feature should add no performance burden for them.
Personally, I am accidentally serializing some long
values that cannot be represented accurately as numbers in JSONJavaScript. Woops! I didn’t notice until I implemented the strict numbers feature for myself.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:1
- Comments:22 (15 by maintainers)
Top GitHub Comments
NaN and ±Infinity should just be serialised as literal “null” instead. I’ve been searching for about half an hour for how to get Jackson to do that, i.e. behave as per the ECMAscript/JSON standard, already, with no success so far…
Ah ok @sbernard31 that makes sense. I agree. I think I misread your comment there, thank you for clarification.