You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When encoding the value, JSONEncoder makes a Double value an Int64 when it doesn't have fractional values.
As seen in the screenshot bellow, the encoder uses the double type when it has fractional part
![](Screen Shot 2020-06-10 at 19.22.46.png)
But when encoding a value that doesn't have a fractional part it losses type information and encode the value as Int64.
![](Screen Shot 2020-06-10 at 19.21.24.png)
The question is if that is intended behavior (optimization) or is indeed a problem? If that is intended behavior is fine because at the end it represents the same value, but I'm just a bit curious to know why the encoder does that 🙂
The text was updated successfully, but these errors were encountered:
As you can see converting a Double to a String is not precise however thats not important here.
Encoding A(20.00) to JSON gives:
code
{"a":20,"b":{"value":20}} code
Its important to note that JSON doesn't differentiate between floating point and integers, all numbers are just represented as a string of digits that may optionally have a decimal point and an exponent. It is upto the decoder to decide how to store it.
So given "20.010000000000002", the only type that can hold it is a Double so it is stored as such. But given "20" an Int64 is a better choice since it can store a large range of integers. The actual value is stored as an NSNumber since it is inside an NSDictionary which only holds reference types.
The other thing to note is that JSONSerialization doesn't know about JSONDecoder, and that ultimately the value will be converted to a Double when creating the A and B instances. It only generates structures consisting of Dictionarys, Arrays, Strings and Numbers.
There is some further discussion about parsing of JSON numbers in the swift-corelibs-foundation version of JSONSerialization in #1655 and #1657
Attachment: Download
Environment
Xcode 11.5
Additional Detail from JIRA
md5: 24b93375887ee6f6f34bb2f0a444e4da
Issue Description:
Exemple:
When encoding the value, JSONEncoder makes a Double value an Int64 when it doesn't have fractional values.
As seen in the screenshot bellow, the encoder uses the double type when it has fractional part
![](Screen Shot 2020-06-10 at 19.22.46.png)
But when encoding a value that doesn't have a fractional part it losses type information and encode the value as Int64.
![](Screen Shot 2020-06-10 at 19.21.24.png)
The question is if that is intended behavior (optimization) or is indeed a problem? If that is intended behavior is fine because at the end it represents the same value, but I'm just a bit curious to know why the encoder does that 🙂
The text was updated successfully, but these errors were encountered: