Skip to content

[SR-2151]NSJSONSerialization.data produces illegal JSON code #540

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 3 commits into from
Aug 18, 2016
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
19 changes: 17 additions & 2 deletions Foundation/NSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

import CoreFoundation

#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
Expand Down Expand Up @@ -240,6 +242,14 @@ private struct JSONWriter {
let pretty: Bool
let writer: (String?) -> Void

private lazy var _numberformatter: CFNumberFormatter = {
let formatter: CFNumberFormatter
formatter = CFNumberFormatterCreate(nil, CFLocaleCopyCurrent(), kCFNumberFormatterNoStyle)
CFNumberFormatterSetProperty(formatter, kCFNumberFormatterMaxFractionDigits, 15._bridgeToObject())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The syntax for bridging has changed; I would suggest to actually just create a NSNumber via NSNumber(value: 15)

CFNumberFormatterSetFormat(formatter, "0.###############"._cfObject)
return formatter
}()

init(pretty: Bool = false, writer: @escaping (String?) -> Void) {
self.pretty = pretty
self.writer = writer
Expand Down Expand Up @@ -298,15 +308,15 @@ private struct JSONWriter {
writer("\"")
}

func serializeNumber(_ num: NSNumber) throws {
mutating func serializeNumber(_ num: NSNumber) throws {
if num.doubleValue.isInfinite || num.doubleValue.isNaN {
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: ["NSDebugDescription" : "Number cannot be infinity or NaN"])
}

// Cannot detect type information (e.g. bool) as there is no objCType property on NSNumber in Swift
// So, just print the number

writer("\(num)")
writer(_serializationString(for: num))
}

mutating func serializeArray(_ array: NSArray) throws {
Expand Down Expand Up @@ -389,6 +399,11 @@ private struct JSONWriter {
writer(" ")
}
}

//[SR-2151] https://bugs.swift.org/browse/SR-2151
private mutating func _serializationString(for number: NSNumber) -> String {
return CFNumberFormatterCreateStringWithNumber(nil, _numberformatter, number._cfObject)._swiftObject
}
}

//MARK: - JSONDeserializer
Expand Down
84 changes: 84 additions & 0 deletions TestFoundation/TestNSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ extension TestNSJSONSerialization {
("test_deserialize_badlyFormedArray", test_deserialize_badlyFormedArray),
("test_deserialize_invalidEscapeSequence", test_deserialize_invalidEscapeSequence),
("test_deserialize_unicodeMissingTrailingSurrogate", test_deserialize_unicodeMissingTrailingSurrogate),
("test_serialize_dictionaryWithDecimal", test_serialize_dictionaryWithDecimal),

]
}

Expand Down Expand Up @@ -622,6 +624,88 @@ extension TestNSJSONSerialization {
XCTAssertEqual(try trySerialize(array2), "[]")
}

//[SR-2151] https://bugs.swift.org/browse/SR-2151
//NSJSONSerialization.data(withJSONObject:options) produces illegal JSON code
func test_serialize_dictionaryWithDecimal() {

//test serialize values less than 1 with maxFractionDigits = 15
func excecute_testSetLessThanOne() {
//expected : input to be serialized
let params = [
("0.1",0.1),
("0.2",0.2),
("0.3",0.3),
("0.4",0.4),
("0.5",0.5),
("0.6",0.6),
("0.7",0.7),
("0.8",0.8),
("0.9",0.9),
("0.23456789012345",0.23456789012345),

("-0.1",-0.1),
("-0.2",-0.2),
("-0.3",-0.3),
("-0.4",-0.4),
("-0.5",-0.5),
("-0.6",-0.6),
("-0.7",-0.7),
("-0.8",-0.8),
("-0.9",-0.9),
("-0.23456789012345",-0.23456789012345),
]
for param in params {
let testDict = [param.0 : param.1]
let str = try? trySerialize(testDict.bridge())
XCTAssertEqual(str!, "{\"\(param.0)\":\(param.1)}", "serialized value should have a decimal places and leading zero")
}
}
//test serialize values grater than 1 with maxFractionDigits = 15
func excecute_testSetGraterThanOne() {
let paramsBove1 = [
("1.1",1.1),
("1.2",1.2),
("1.23456789012345",1.23456789012345),
("-1.1",-1.1),
("-1.2",-1.2),
("-1.23456789012345",-1.23456789012345),
]
for param in paramsBove1 {
let testDict = [param.0 : param.1]
let str = try? trySerialize(testDict.bridge())
XCTAssertEqual(str!, "{\"\(param.0)\":\(param.1)}", "serialized Double should have a decimal places and leading value")
}
}

//test serialize values for whole integer where the input is in Double format
func excecute_testWholeNumbersWithDoubleAsInput() {

let paramsWholeNumbers = [
("-1" ,-1.0),
("0" ,0.0),
("1" ,1.0),
]
for param in paramsWholeNumbers {
let testDict = [param.0 : param.1]
let str = try? trySerialize(testDict.bridge())
XCTAssertEqual(str!, "{\"\(param.0)\":\(param.0._bridgeToObject().intValue)}", "expect that serialized value should not contain trailing zero or decimal as they are whole numbers ")
}
}

func excecute_testWholeNumbersWithIntInput() {
for i in -10..<10 {
let iStr = "\(i)"
let testDict = [iStr : i]
let str = try? trySerialize(testDict.bridge())
XCTAssertEqual(str!, "{\"\(iStr)\":\(i)}", "expect that serialized value should not contain trailing zero or decimal as they are whole numbers ")
}
}
excecute_testSetLessThanOne()
excecute_testSetGraterThanOne()
excecute_testWholeNumbersWithDoubleAsInput()
excecute_testWholeNumbersWithIntInput()
}

func test_serialize_null() {
let arr = [NSNull()].bridge()
XCTAssertEqual(try trySerialize(arr), "[null]")
Expand Down