Skip to content

Commit 1e6d34c

Browse files
author
“saiHemak”
committed
Cannot JSON serialize array with boolean value - bug
1 parent 1924941 commit 1e6d34c

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

Foundation/NSJSONSerialization.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ open class JSONSerialization : NSObject {
6161
}
6262

6363
// object is NSNumber and is not NaN or infinity
64-
if let number = obj as? NSNumber {
64+
if let number = _SwiftValue.store(obj) as? NSNumber {
6565
let invalid = number.doubleValue.isInfinite || number.doubleValue.isNaN
6666
return !invalid
6767
}
@@ -285,6 +285,8 @@ private struct JSONWriter {
285285
try serializeDictionary(dict)
286286
} else if let null = obj as? NSNull {
287287
try serializeNull(null)
288+
} else if let boolVal = obj as? Bool {
289+
try serializeNumber(NSNumber(booleanLiteral: boolVal))
288290
}
289291
else {
290292
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Invalid object cannot be serialized"])

TestFoundation/TestNSJSONSerialization.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,7 @@ extension TestNSJSONSerialization {
597597
("test_jsonObjectToOutputStreamFile", test_jsonObjectToOutputStreamFile),
598598
("test_invalidJsonObjectToStreamBuffer", test_invalidJsonObjectToStreamBuffer),
599599
("test_jsonObjectToOutputStreamInsufficeintBuffer", test_jsonObjectToOutputStreamInsufficeintBuffer),
600+
("test_booleanJSONObject", test_booleanJSONObject),
600601
]
601602
}
602603

@@ -928,6 +929,16 @@ extension TestNSJSONSerialization {
928929
XCTAssertThrowsError(try JSONSerialization.writeJSONObject(str, toStream: outputStream, options: []))
929930
}
930931

932+
func test_booleanJSONObject() {
933+
do {
934+
let mydata = try JSONSerialization.data(withJSONObject: [true])
935+
XCTAssertEqual(String(data: mydata, encoding: String.Encoding.utf8),"[1]")
936+
} catch {
937+
XCTFail("Failed during serialization")
938+
}
939+
XCTAssertTrue(JSONSerialization.isValidJSONObject([1]))
940+
}
941+
931942
private func createTestFile(_ path: String,_contents: Data) -> String? {
932943
let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/"
933944
do {

0 commit comments

Comments
 (0)