Skip to content

[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

Conversation

millenomi
Copy link
Contributor

Darwin encodes these as an empty array ([]), but SCF was encoding an empty JSON object instead ({}). Fixes https://bugs.swift.org/browse/SR-15781.

… 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.
@millenomi
Copy link
Contributor Author

@swift-ci please test

Copy link
Contributor

@parkera parkera left a 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)
Copy link

@vlm vlm Feb 1, 2022

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 {}).

Copy link
Contributor Author

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)!
Copy link

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.

Copy link
Contributor Author

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 {}.

@millenomi millenomi merged commit ffeb0f8 into swiftlang:release/5.5 Feb 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants