Skip to content

Commit

Permalink
Drop NS from JSONSerialization
Browse files Browse the repository at this point in the history
  • Loading branch information
phausler committed May 23, 2016
1 parent 5f7f6f1 commit b914527
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 45 deletions.
40 changes: 21 additions & 19 deletions Foundation/NSJSONSerialization.swift
Expand Up @@ -13,20 +13,22 @@
import Glibc import Glibc
#endif #endif


public struct NSJSONReadingOptions : OptionSet { extension JSONSerialization {
public let rawValue : UInt public struct ReadingOptions : OptionSet {
public init(rawValue: UInt) { self.rawValue = rawValue } public let rawValue : UInt

public init(rawValue: UInt) { self.rawValue = rawValue }
public static let mutableContainers = NSJSONReadingOptions(rawValue: 1 << 0)
public static let mutableLeaves = NSJSONReadingOptions(rawValue: 1 << 1) public static let mutableContainers = ReadingOptions(rawValue: 1 << 0)
public static let allowFragments = NSJSONReadingOptions(rawValue: 1 << 2) public static let mutableLeaves = ReadingOptions(rawValue: 1 << 1)
} public static let allowFragments = ReadingOptions(rawValue: 1 << 2)
}


public struct NSJSONWritingOptions : OptionSet { public struct WritingOptions : OptionSet {
public let rawValue : UInt public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue } public init(rawValue: UInt) { self.rawValue = rawValue }


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




Expand All @@ -40,7 +42,7 @@ public struct NSJSONWritingOptions : OptionSet {
- `NSNumber`s are not NaN or infinity - `NSNumber`s are not NaN or infinity
*/ */


public class NSJSONSerialization : NSObject { public class JSONSerialization : NSObject {


/* Determines whether the given object can be converted to JSON. /* Determines whether the given object can be converted to JSON.
Other rules may apply. Calling this method or attempting a conversion are the definitive ways Other rules may apply. Calling this method or attempting a conversion are the definitive ways
Expand Down Expand Up @@ -96,7 +98,7 @@ public class NSJSONSerialization : NSObject {


/* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8. /* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.
*/ */
public class func data(withJSONObject obj: AnyObject, options opt: NSJSONWritingOptions = []) throws -> NSData { public class func data(withJSONObject obj: AnyObject, options opt: WritingOptions = []) throws -> NSData {
guard obj is NSArray || obj is NSDictionary else { guard obj is NSArray || obj is NSDictionary else {
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [ throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [
"NSDebugDescription" : "Top-level object was not NSArray or NSDictionary" "NSDebugDescription" : "Top-level object was not NSArray or NSDictionary"
Expand All @@ -123,7 +125,7 @@ public class NSJSONSerialization : NSObject {
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8. The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
*/ */
/// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place. /// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place.
public class func jsonObject(with data: NSData, options opt: NSJSONReadingOptions = []) throws -> Any { public class func jsonObject(with data: NSData, options opt: ReadingOptions = []) throws -> Any {


let bytes = UnsafePointer<UInt8>(data.bytes) let bytes = UnsafePointer<UInt8>(data.bytes)
let encoding: NSStringEncoding let encoding: NSStringEncoding
Expand Down Expand Up @@ -155,20 +157,20 @@ public class NSJSONSerialization : NSObject {


/* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method. /* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method.
*/ */
public class func writeJSONObject(_ obj: AnyObject, toStream stream: NSOutputStream, options opt: NSJSONWritingOptions) throws -> Int { public class func writeJSONObject(_ obj: AnyObject, toStream stream: NSOutputStream, options opt: WritingOptions) throws -> Int {
NSUnimplemented() NSUnimplemented()
} }


/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method. /* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
*/ */
public class func jsonObject(with stream: NSInputStream, options opt: NSJSONReadingOptions = []) throws -> AnyObject { public class func jsonObject(with stream: NSInputStream, options opt: ReadingOptions = []) throws -> AnyObject {
NSUnimplemented() NSUnimplemented()
} }
} }


//MARK: - Encoding Detection //MARK: - Encoding Detection


internal extension NSJSONSerialization { internal extension JSONSerialization {


/// Detect the encoding format of the NSData contents /// Detect the encoding format of the NSData contents
class func detectEncoding(_ bytes: UnsafePointer<UInt8>, _ length: Int) -> NSStringEncoding { class func detectEncoding(_ bytes: UnsafePointer<UInt8>, _ length: Int) -> NSStringEncoding {
Expand Down
52 changes: 26 additions & 26 deletions TestFoundation/TestNSJSONSerialization.swift
Expand Up @@ -47,7 +47,7 @@ extension TestNSJSONSerialization {
func test_JSONObjectWithData_emptyObject() { func test_JSONObjectWithData_emptyObject() {
let subject = NSData(bytes: UnsafePointer<Void>([UInt8]([0x7B, 0x7D])), length: 2) let subject = NSData(bytes: UnsafePointer<Void>([UInt8]([0x7B, 0x7D])), length: 2)


let object = try! NSJSONSerialization.jsonObject(with: subject, options: []) as? [String:Any] let object = try! JSONSerialization.jsonObject(with: subject, options: []) as? [String:Any]
XCTAssertEqual(object?.count, 0) XCTAssertEqual(object?.count, 0)
} }


Expand Down Expand Up @@ -75,7 +75,7 @@ extension TestNSJSONSerialization {
] ]


for (description, encoded) in subjects { for (description, encoded) in subjects {
let result = try? NSJSONSerialization.jsonObject(with: NSData(bytes:UnsafePointer<Void>(encoded), length: encoded.count), options: []) let result = try? JSONSerialization.jsonObject(with: NSData(bytes:UnsafePointer<Void>(encoded), length: encoded.count), options: [])
XCTAssertNotNil(result, description) XCTAssertNotNil(result, description)
} }
} }
Expand Down Expand Up @@ -125,7 +125,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let t = try NSJSONSerialization.jsonObject(with: data, options: []) let t = try JSONSerialization.jsonObject(with: data, options: [])
let result = t as? [String: Any] let result = t as? [String: Any]
XCTAssertEqual(result?.count, 0) XCTAssertEqual(result?.count, 0)
} catch { } catch {
Expand All @@ -141,7 +141,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [String: Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
XCTAssertEqual(result?["hello"] as? String, "world") XCTAssertEqual(result?["hello"] as? String, "world")
XCTAssertEqual(result?["swift"] as? String, "rocks") XCTAssertEqual(result?["swift"] as? String, "rocks")
} }
Expand All @@ -158,7 +158,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [String : Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
XCTAssertEqual(result?["title"] as? String, " hello world!!") XCTAssertEqual(result?["title"] as? String, " hello world!!")
} catch{ } catch{
XCTFail("Error thrown: \(error)") XCTFail("Error thrown: \(error)")
Expand All @@ -176,7 +176,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?.count, 0) XCTAssertEqual(result?.count, 0)
} catch { } catch {
XCTFail("Unexpected error: \(error)") XCTFail("Unexpected error: \(error)")
Expand All @@ -192,7 +192,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "hello") XCTAssertEqual(result?[0] as? String, "hello")
XCTAssertEqual(result?[1] as? String, "swift⚡️") XCTAssertEqual(result?[1] as? String, "swift⚡️")
} }
Expand All @@ -211,7 +211,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "unicode") XCTAssertEqual(result?[0] as? String, "unicode")
XCTAssertEqual(result?[1] as? String, "Ģ") XCTAssertEqual(result?[1] as? String, "Ģ")
XCTAssertEqual(result?[2] as? String, "😢") XCTAssertEqual(result?[2] as? String, "😢")
Expand All @@ -231,7 +231,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? Bool, true) XCTAssertEqual(result?[0] as? Bool, true)
XCTAssertEqual(result?[1] as? Bool, false) XCTAssertEqual(result?[1] as? Bool, false)
XCTAssertEqual(result?[2] as? String, "hello") XCTAssertEqual(result?[2] as? String, "hello")
Expand All @@ -254,7 +254,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? Int, 1) XCTAssertEqual(result?[0] as? Int, 1)
XCTAssertEqual(result?[1] as? Int, -1) XCTAssertEqual(result?[1] as? Int, -1)
XCTAssertEqual(result?[2] as? Double, 1.3) XCTAssertEqual(result?[2] as? Double, 1.3)
Expand All @@ -275,7 +275,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let res = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let res = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
let result = res?.flatMap { $0 as? String } let result = res?.flatMap { $0 as? String }
XCTAssertEqual(result?[0], "\"") XCTAssertEqual(result?[0], "\"")
XCTAssertEqual(result?[1], "\\") XCTAssertEqual(result?[1], "\\")
Expand All @@ -297,7 +297,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "") XCTAssertEqual(result?[0] as? String, "")
} catch { } catch {
XCTFail("Unexpected error: \(error)") XCTFail("Unexpected error: \(error)")
Expand All @@ -311,7 +311,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any] let result = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "\u{1D11E}") XCTAssertEqual(result?[0] as? String, "\u{1D11E}")
} catch { } catch {
XCTFail("Unexpected error: \(error)") XCTFail("Unexpected error: \(error)")
Expand All @@ -327,7 +327,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let result = try NSJSONSerialization.jsonObject(with: data, options: .allowFragments) as? Int let result = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Int
XCTAssertEqual(result, 3) XCTAssertEqual(result, 3)
} }
} catch { } catch {
Expand All @@ -344,7 +344,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: UnterminatedString") XCTFail("Expected error: UnterminatedString")
} catch { } catch {
// Passing case; the object as unterminated // Passing case; the object as unterminated
Expand All @@ -359,7 +359,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Missing key for value") XCTFail("Expected error: Missing key for value")
} catch { } catch {
// Passing case; the key was missing for a value // Passing case; the key was missing for a value
Expand All @@ -374,7 +374,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Unexpected end of file") XCTFail("Expected error: Unexpected end of file")
} catch { } catch {
// Success // Success
Expand All @@ -389,7 +389,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid value") XCTFail("Expected error: Invalid value")
} catch { } catch {
// Passing case; the value is invalid // Passing case; the value is invalid
Expand All @@ -404,7 +404,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid value") XCTFail("Expected error: Invalid value")
} catch { } catch {
// passing case the value is invalid // passing case the value is invalid
Expand All @@ -419,7 +419,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid value") XCTFail("Expected error: Invalid value")
} catch { } catch {
// Passing case; the element in the array is missing // Passing case; the element in the array is missing
Expand All @@ -434,7 +434,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Badly formed array") XCTFail("Expected error: Badly formed array")
} catch { } catch {
// Passing case; the array is malformed // Passing case; the array is malformed
Expand All @@ -449,7 +449,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) let _ = try JSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid escape sequence") XCTFail("Expected error: Invalid escape sequence")
} catch { } catch {
// Passing case; the escape sequence is invalid // Passing case; the escape sequence is invalid
Expand All @@ -463,7 +463,7 @@ extension TestNSJSONSerialization {
XCTFail("Unable to convert string to data") XCTFail("Unable to convert string to data")
return return
} }
let _ = try NSJSONSerialization.jsonObject(with: data, options: []) as? [String] let _ = try JSONSerialization.jsonObject(with: data, options: []) as? [String]
XCTFail("Expected error: Missing Trailing Surrogate") XCTFail("Expected error: Missing Trailing Surrogate")
} catch { } catch {
// Passing case; the unicode character is malformed // Passing case; the unicode character is malformed
Expand Down Expand Up @@ -525,7 +525,7 @@ extension TestNSJSONSerialization {
) )
] ]
for testCase in trueJSON { for testCase in trueJSON {
XCTAssertTrue(NSJSONSerialization.isValidJSONObject(testCase)) XCTAssertTrue(JSONSerialization.isValidJSONObject(testCase))
} }
} }


Expand Down Expand Up @@ -574,7 +574,7 @@ extension TestNSJSONSerialization {
) )
] ]
for testCase in falseJSON { for testCase in falseJSON {
XCTAssertFalse(NSJSONSerialization.isValidJSONObject(testCase)) XCTAssertFalse(JSONSerialization.isValidJSONObject(testCase))
} }
} }


Expand All @@ -597,7 +597,7 @@ extension TestNSJSONSerialization {
} }


func trySerialize(_ obj: AnyObject) throws -> String { func trySerialize(_ obj: AnyObject) throws -> String {
let data = try NSJSONSerialization.data(withJSONObject: obj, options: []) let data = try JSONSerialization.data(withJSONObject: obj, options: [])
guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) else { guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) else {
XCTFail("Unable to create string") XCTFail("Unable to create string")
return "" return ""
Expand Down

0 comments on commit b914527

Please sign in to comment.