diff --git a/Foundation/NSJSONSerialization.swift b/Foundation/NSJSONSerialization.swift index 31ec8ba385..00d431a701 100644 --- a/Foundation/NSJSONSerialization.swift +++ b/Foundation/NSJSONSerialization.swift @@ -61,7 +61,7 @@ open class JSONSerialization : NSObject { } // object is NSNumber and is not NaN or infinity - if let number = obj as? NSNumber { + if let number = _SwiftValue.store(obj) as? NSNumber { let invalid = number.doubleValue.isInfinite || number.doubleValue.isNaN return !invalid } @@ -273,11 +273,7 @@ private struct JSONWriter { if let str = obj as? String { try serializeString(str) - } else if let num = obj as? Int { - try serializeNumber(NSNumber(value: num)) - } else if let num = obj as? Double { - try serializeNumber(NSNumber(value: num)) - } else if let num = obj as? NSNumber { + } else if let num = _SwiftValue.store(obj) as? NSNumber { try serializeNumber(num) } else if let array = obj as? Array { try serializeArray(array) @@ -285,6 +281,8 @@ private struct JSONWriter { try serializeDictionary(dict) } else if let null = obj as? NSNull { try serializeNull(null) + } else if let boolVal = obj as? Bool { + try serializeNumber(NSNumber(value: boolVal)) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Invalid object cannot be serialized"]) diff --git a/TestFoundation/TestNSJSONSerialization.swift b/TestFoundation/TestNSJSONSerialization.swift index 320b3df496..d40a1c0653 100644 --- a/TestFoundation/TestNSJSONSerialization.swift +++ b/TestFoundation/TestNSJSONSerialization.swift @@ -597,6 +597,7 @@ extension TestNSJSONSerialization { ("test_jsonObjectToOutputStreamFile", test_jsonObjectToOutputStreamFile), ("test_invalidJsonObjectToStreamBuffer", test_invalidJsonObjectToStreamBuffer), ("test_jsonObjectToOutputStreamInsufficeintBuffer", test_jsonObjectToOutputStreamInsufficeintBuffer), + ("test_booleanJSONObject", test_booleanJSONObject), ] } @@ -928,6 +929,16 @@ extension TestNSJSONSerialization { XCTAssertThrowsError(try JSONSerialization.writeJSONObject(str, toStream: outputStream, options: [])) } + func test_booleanJSONObject() { + do { + let mydata = try JSONSerialization.data(withJSONObject: [true]) + XCTAssertEqual(String(data: mydata, encoding: String.Encoding.utf8), "[1]") + } catch { + XCTFail("Failed during serialization") + } + XCTAssertTrue(JSONSerialization.isValidJSONObject([1])) + } + private func createTestFile(_ path: String,_contents: Data) -> String? { let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/" do {