Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-9279] JSONEncoder with dateEncodingStrategy of millisecondsSince1970 produces Float type in resulting JSON #3587

Open
swift-ci opened this issue Nov 16, 2018 · 1 comment

Comments

@swift-ci
Copy link
Contributor

Previous ID SR-9279
Radar None
Original Reporter rkhalili (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Foundation
Labels Bug, Codable
Assignee None
Priority Medium

md5: 26375280f8cb81c834f177bb618146aa

Issue Description:

When JSON-encoding a dictionary with a Date object, and specifying millisecondsSince1970 for the date encoding strategy, the resulting encoded value for the Date object is a floating point number with some amount of decimal places, instead of an integer representing milliseconds. This doesn't seem correct, I feel like this can cause incompatibility with systems or APIs that don't expect floats for millisecond values (which was the case for my company's Java back-end API).

To reproduce:

let test = ["key": Date()]
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .millisecondsSince1970
if let result = try? encoder.encode(test) {
    if let backToString = String(data: result, encoding: .utf8) {
        print("JSON: " + backToString)
    }
}

Expected output:

JSON: {"key":1542355551611}

Actual output:

JSON: {"key":1542355551611.2129}

@swift-ci
Copy link
Contributor Author

Comment by Charles Maria Tor (JIRA)

I don't think this is a bug, truncating the fractional bits would mean that a round-trip through JSON would be lossy in precision.

If you need this behaviour, customise your Date encoding by manually implementing the encode function and encoding

Int(date.timeIntervalSince1970 * 1000)

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
@shahmishal shahmishal transferred this issue from apple/swift May 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant