Skip to content

[5.0] SR-9828: JSONEncoder keyEncodingStrategy does not work on Linux #1882

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
merged 1 commit into from
Feb 8, 2019
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
60 changes: 37 additions & 23 deletions Foundation/JSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -383,30 +383,44 @@ fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingCon
self.container = container
}

// MARK: - Coding Path Operations

private func _converted(_ key: CodingKey) -> CodingKey {
switch encoder.options.keyEncodingStrategy {
case .useDefaultKeys:
return key
case .convertToSnakeCase:
let newKeyString = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue)
return _JSONKey(stringValue: newKeyString, intValue: key.intValue)
case .custom(let converter):
return converter(codingPath + [key])
}
}

// MARK: - KeyedEncodingContainerProtocol Methods

public mutating func encodeNil(forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = NSNull() }
public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: String, forKey key: Key) throws { self.container[key.stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encodeNil(forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = NSNull() }
public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }
public mutating func encode(_ value: String, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) }

public mutating func encode(_ value: Float, forKey key: Key) throws {
// Since the float may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
#if DEPLOYMENT_RUNTIME_SWIFT
self.container[key.stringValue._bridgeToObjectiveC()] = try self.encoder.box(value)
self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value)
#else
self.container[key.stringValue] = try self.encoder.box(value)
self.container[_converted(key).stringValue] = try self.encoder.box(value)
#endif
}

Expand All @@ -415,28 +429,28 @@ fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingCon
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
#if DEPLOYMENT_RUNTIME_SWIFT
self.container[key.stringValue._bridgeToObjectiveC()] = try self.encoder.box(value)
self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value)
#else
self.container[key.stringValue] = try self.encoder.box(value)
self.container[_converted(key).stringValue] = try self.encoder.box(value)
#endif
}

public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
#if DEPLOYMENT_RUNTIME_SWIFT
self.container[key.stringValue._bridgeToObjectiveC()] = try self.encoder.box(value)
self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value)
#else
self.container[key.stringValue] = try self.encoder.box(value)
self.container[_converted(key).stringValue] = try self.encoder.box(value)
#endif
}

public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
let dictionary = NSMutableDictionary()
#if DEPLOYMENT_RUNTIME_SWIFT
self.container[key.stringValue._bridgeToObjectiveC()] = dictionary
self.container[_converted(key).stringValue._bridgeToObjectiveC()] = dictionary
#else
self.container[key.stringValue] = dictionary
self.container[_converted(key).stringValue] = dictionary
#endif

self.codingPath.append(key)
Expand All @@ -449,9 +463,9 @@ fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingCon
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
let array = NSMutableArray()
#if DEPLOYMENT_RUNTIME_SWIFT
self.container[key.stringValue._bridgeToObjectiveC()] = array
self.container[_converted(key).stringValue._bridgeToObjectiveC()] = array
#else
self.container[key.stringValue] = array
self.container[_converted(key).stringValue] = array
#endif

self.codingPath.append(key)
Expand Down
73 changes: 73 additions & 0 deletions TestFoundation/TestJSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,78 @@ class TestJSONEncoder : XCTestCase {
testErrorThrown("Double", "2.7976931348623158e+308", errorMessage: "The given data was not valid JSON.")
}

func test_snake_case_encoding() throws {
struct MyTestData: Codable, Equatable {
let thisIsAString: String
let thisIsABool: Bool
let thisIsAnInt: Int
let thisIsAnInt8: Int8
let thisIsAnInt16: Int16
let thisIsAnInt32: Int32
let thisIsAnInt64: Int64
let thisIsAUint: UInt
let thisIsAUint8: UInt8
let thisIsAUint16: UInt16
let thisIsAUint32: UInt32
let thisIsAUint64: UInt64
let thisIsAFloat: Float
let thisIsADouble: Double
let thisIsADate: Date
let thisIsAnArray: Array<Int>
let thisIsADictionary: Dictionary<String, Bool>
}

let data = MyTestData(thisIsAString: "Hello",
thisIsABool: true,
thisIsAnInt: 1,
thisIsAnInt8: 2,
thisIsAnInt16: 3,
thisIsAnInt32: 4,
thisIsAnInt64: 5,
thisIsAUint: 6,
thisIsAUint8: 7,
thisIsAUint16: 8,
thisIsAUint32: 9,
thisIsAUint64: 10,
thisIsAFloat: 11,
thisIsADouble: 12,
thisIsADate: Date.init(timeIntervalSince1970: 0),
thisIsAnArray: [1, 2, 3],
thisIsADictionary: [ "trueValue": true, "falseValue": false]
)

let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
encoder.dateEncodingStrategy = .iso8601
let encodedData = try encoder.encode(data)
guard let jsonObject = try JSONSerialization.jsonObject(with: encodedData) as? [String: Any] else {
XCTFail("Cant decode json object")
return
}
XCTAssertEqual(jsonObject["this_is_a_string"] as? String, "Hello")
XCTAssertEqual(jsonObject["this_is_a_bool"] as? Bool, true)
XCTAssertEqual(jsonObject["this_is_an_int"] as? Int, 1)
XCTAssertEqual(jsonObject["this_is_an_int8"] as? Int8, 2)
XCTAssertEqual(jsonObject["this_is_an_int16"] as? Int16, 3)
XCTAssertEqual(jsonObject["this_is_an_int32"] as? Int32, 4)
XCTAssertEqual(jsonObject["this_is_an_int64"] as? Int64, 5)
XCTAssertEqual(jsonObject["this_is_a_uint"] as? UInt, 6)
XCTAssertEqual(jsonObject["this_is_a_uint8"] as? UInt8, 7)
XCTAssertEqual(jsonObject["this_is_a_uint16"] as? UInt16, 8)
XCTAssertEqual(jsonObject["this_is_a_uint32"] as? UInt32, 9)
XCTAssertEqual(jsonObject["this_is_a_uint64"] as? UInt64, 10)
XCTAssertEqual(jsonObject["this_is_a_float"] as? Float, 11)
XCTAssertEqual(jsonObject["this_is_a_double"] as? Double, 12)
XCTAssertEqual(jsonObject["this_is_a_date"] as? String, "1970-01-01T00:00:00Z")
XCTAssertEqual(jsonObject["this_is_an_array"] as? [Int], [1, 2, 3])
XCTAssertEqual(jsonObject["this_is_a_dictionary"] as? [String: Bool], ["true_value": true, "false_value": false ])

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
let decodedData = try decoder.decode(MyTestData.self, from: encodedData)
XCTAssertEqual(data, decodedData)
}

// MARK: - Helper Functions
private var _jsonEmptyDictionary: Data {
Expand Down Expand Up @@ -1197,6 +1269,7 @@ extension TestJSONEncoder {
("test_codingOfString", test_codingOfString),
("test_codingOfURL", test_codingOfURL),
("test_numericLimits", test_numericLimits),
("test_snake_case_encoding", test_snake_case_encoding),
]
}
}