FasterXML / FasterXML/jackson-databind
Add serialization feature: strict numbers (FPs that fit `long`, Javascript compatibility)
- 主要言語
- Java
- スター
- 3.7k
- フォーク
- 1.5k
- 平均マージ
- 3日 6時間
- マージ済み PR(30日)
- 28
説明
This 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`:
1. Attempting to serialize `+Infinity`, `-Infinity`, or `NaN`
2. Attempting to serialize a `long` that cannot be represented as a numerically-equivalent `double`
# +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 ~~JSON~~JavaScript. 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 ~~JSON~~JavaScript. Woops! I didn't notice until I implemented the strict numbers feature for myself.
コントリビューションガイド
このリポジトリのコントリビューションガイドは索引されていません
評価
この issue はまだ評価されていません。