-
Notifications
You must be signed in to change notification settings - Fork 1.2k
[5.5] Prevent empty dictionary with non-String keys from encoding as a JSON object. #3136
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
[5.5] Prevent empty dictionary with non-String keys from encoding as a JSON object. #3136
Conversation
… object. Darwin encodes these as an empty array (`[]`), but SCF was encoding an empty JSON object instead (`{}`). Fixes https://bugs.swift.org/browse/SR-15781.
@swift-ci please test |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks good to take for 5.5
let toEncode = Something(dict: [:]) | ||
let data = try JSONEncoder().encode(toEncode) | ||
let result = try JSONDecoder().decode(Something.self, from: data) | ||
XCTAssertEqual(result.dict.count, 0) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it make sense to test the actual encoding too, to ensure the JSON array is produced? ([]
vs {}
).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That makes sense. I'll add it in a follow-up.
let result = try JSONDecoder().decode(Something.self, from: data) | ||
XCTAssertEqual(result.dict.count, 0) | ||
} | ||
|
||
// MARK: - Helper Functions | ||
private var _jsonEmptyDictionary: Data { | ||
return "{}".data(using: .utf8)! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we guarantee the empty dictionary is always encoded as {}
regardless of type? If not, the variable name might be misleading.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The empty dictionary is not always encoded as []
regardless of type. Specifically, <T: Encodable> [String: T]
are encoded as JSON objects, and an empty dictionary of that type is encoded as {}
.
Darwin encodes these as an empty array (
[]
), but SCF was encoding an empty JSON object instead ({}
). Fixes https://bugs.swift.org/browse/SR-15781.