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

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Sources/Foundation/JSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -506,8 +506,8 @@ extension _SpecialTreatmentEncoder {
return .string(url.absoluteString)
case let decimal as Decimal:
return .number(decimal.description)
case let object as [String: Encodable]:
return try self.wrapObject(object, for: additionalKey)
case let object as _JSONStringDictionaryEncodableMarker:
return try self.wrapObject(object as! [String: Encodable], for: additionalKey)
default:
let encoder = self.getEncoder(for: additionalKey)
try encodable.encode(to: encoder)
Expand Down
34 changes: 34 additions & 0 deletions Tests/Foundation/Tests/TestJSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,39 @@ class TestJSONEncoder : XCTestCase {
XCTAssertEqual(JSONEncoder.OutputFormatting.withoutEscapingSlashes.rawValue, 8)
}

func test_SR17581_codingEmptyDictionaryWithNonstringKeyDoesRoundtrip() throws {
struct Something: Codable {
struct Key: Codable, Hashable {
var x: String
}

var dict: [Key: String]

enum CodingKeys: String, CodingKey {
case dict
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.dict = try container.decode([Key: String].self, forKey: .dict)
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(dict, forKey: .dict)
}

init(dict: [Key: String]) {
self.dict = dict
}
}

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.

}

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

Expand Down Expand Up @@ -1471,6 +1504,7 @@ extension TestJSONEncoder {
("test_dictionary_snake_case_decoding", test_dictionary_snake_case_decoding),
("test_dictionary_snake_case_encoding", test_dictionary_snake_case_encoding),
("test_OutputFormattingValues", test_OutputFormattingValues),
("test_SR17581_codingEmptyDictionaryWithNonstringKeyDoesRoundtrip", test_SR17581_codingEmptyDictionaryWithNonstringKeyDoesRoundtrip),
]
}
}