Skip to content

JSONSerialization: add WritingOptions.sortedKeys #1102

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 4 commits into from
Jul 10, 2017
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
40 changes: 33 additions & 7 deletions Foundation/NSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ extension JSONSerialization {
public init(rawValue: UInt) { self.rawValue = rawValue }

public static let prettyPrinted = WritingOptions(rawValue: 1 << 0)
public static let sortedKeys = WritingOptions(rawValue: 1 << 1)
}
}

Expand Down Expand Up @@ -116,6 +117,7 @@ open class JSONSerialization : NSObject {

var writer = JSONWriter(
pretty: opt.contains(.prettyPrinted),
sortedKeys: opt.contains(.sortedKeys),
writer: { (str: String?) in
if let str = str {
jsonStr.append(str)
Expand Down Expand Up @@ -289,6 +291,7 @@ private struct JSONWriter {
private let maxIntLength = String(describing: Int.max).characters.count
var indent = 0
let pretty: Bool
let sortedKeys: Bool
let writer: (String?) -> Void

private lazy var _numberformatter: CFNumberFormatter = {
Expand All @@ -299,8 +302,9 @@ private struct JSONWriter {
return formatter
}()

init(pretty: Bool = false, writer: @escaping (String?) -> Void) {
init(pretty: Bool = false, sortedKeys: Bool = false, writer: @escaping (String?) -> Void) {
self.pretty = pretty
self.sortedKeys = sortedKeys
self.writer = writer
}

Expand Down Expand Up @@ -499,10 +503,10 @@ private struct JSONWriter {
writer("\n")
incAndWriteIndent()
}

var first = true
for (key, value) in dict {

func serializeDictionaryElement(key: AnyHashable, value: Any) throws {
if first {
first = false
} else if pretty {
Expand All @@ -511,15 +515,37 @@ private struct JSONWriter {
} else {
writer(",")
}
if key is String {
try serializeString(key as! String)

if let key = key as? String {
try serializeString(key)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
}
pretty ? writer(": ") : writer(":")
try serializeJSON(value)
}

if sortedKeys {
let elems = try dict.sorted(by: { a, b in
guard let a = a.key as? String,
let b = b.key as? String else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
}
let options: NSString.CompareOptions = [.numeric, .caseInsensitive, .forcedOrdering]
let range: Range<String.Index> = a.startIndex..<a.endIndex
let locale = NSLocale.systemLocale()

return a.compare(b, options: options, range: range, locale: locale) == .orderedAscending
})
for elem in elems {
try serializeDictionaryElement(key: elem.key, value: elem.value)
}
} else {
for (key, value) in dict {
try serializeDictionaryElement(key: key, value: value)
}
}

if pretty {
writer("\n")
decAndWriteIndent()
Expand Down
18 changes: 16 additions & 2 deletions TestFoundation/TestNSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -945,11 +945,12 @@ extension TestNSJSONSerialization {
("test_booleanJSONObject", test_booleanJSONObject),
("test_serialize_dictionaryWithDecimal", test_serialize_dictionaryWithDecimal),
("test_serializeDecimalNumberJSONObject", test_serializeDecimalNumberJSONObject),
("test_serializeSortedKeys", test_serializeSortedKeys),
]
}

func trySerialize(_ obj: Any) throws -> String {
let data = try JSONSerialization.data(withJSONObject: obj, options: [])
func trySerialize(_ obj: Any, options: JSONSerialization.WritingOptions = []) throws -> String {
let data = try JSONSerialization.data(withJSONObject: obj, options: options)
guard let string = String(data: data, encoding: .utf8) else {
XCTFail("Unable to create string")
return ""
Expand Down Expand Up @@ -1334,6 +1335,19 @@ extension TestNSJSONSerialization {
} catch {
XCTFail("Failed during serialization")
}
}

func test_serializeSortedKeys() {
var dict: [String: Any]

dict = ["z": 1, "y": 1, "x": 1, "w": 1, "v": 1, "u": 1, "t": 1, "s": 1, "r": 1, "q": 1, ]
XCTAssertEqual(try trySerialize(dict, options: .sortedKeys), "{\"q\":1,\"r\":1,\"s\":1,\"t\":1,\"u\":1,\"v\":1,\"w\":1,\"x\":1,\"y\":1,\"z\":1}")

dict = ["aaaa": 1, "aaa": 1, "aa": 1, "a": 1]
XCTAssertEqual(try trySerialize(dict, options: .sortedKeys), "{\"a\":1,\"aa\":1,\"aaa\":1,\"aaaa\":1}")

dict = ["c": ["c":1,"b":1,"a":1],"b":["c":1,"b":1,"a":1],"a":["c":1,"b":1,"a":1]]
XCTAssertEqual(try trySerialize(dict, options: .sortedKeys), "{\"a\":{\"a\":1,\"b\":1,\"c\":1},\"b\":{\"a\":1,\"b\":1,\"c\":1},\"c\":{\"a\":1,\"b\":1,\"c\":1}}")
}

fileprivate func createTestFile(_ path: String,_contents: Data) -> String? {
Expand Down