0001 // Copyright (C) 2016 Big Nerd Ranch, Inc. Licensed under the MIT license WITHOUT ANY WARRANTY. 0002 0003 import Foundation 0004 0005 // MARK: - Serialize JSON 0006 0007 extension JSON { 0008 0009 /// Attempt to serialize `JSON` into an `NSData`. 0010 /// - returns: A byte-stream containing the `JSON` ready for wire transfer. 0011 /// - throws: Errors that arise from `NSJSONSerialization`. 0012 /// - see: Foundation.NSJSONSerialization 0013 public func serialize() throws -> NSData { 0014 let obj: AnyObject = toNSJSONSerializationObject() 0015 return try NSJSONSerialization.dataWithJSONObject(obj, options: []) 0016 } 0017 0018 /// A function to help with the serialization of `JSON`. 0019 /// - returns: An `AnyObject` suitable for `NSJSONSerialization`'s use. 0020 private func toNSJSONSerializationObject() -> AnyObject { 0021 switch self { 0022 case .Array(let jsonArray): 0023 return jsonArray.map { $0.toNSJSONSerializationObject() } 0024 case .Dictionary(let jsonDictionary): 0025 var cocoaDictionary = Swift.Dictionary<Swift.String, AnyObject>(minimumCapacity: jsonDictionary.count) 0026 for (key, json) in jsonDictionary { 0027 cocoaDictionary[key] = json.toNSJSONSerializationObject() 0028 } 0029 return cocoaDictionary 0030 case .String(let str): 0031 return str 0032 case .Double(let num): 0033 return num 0034 case .Int(let int): 0035 return int 0036 case .Bool(let b): 0037 return b 0038 case .Null: 0039 return NSNull() 0040 } 0041 0042 } 0043 } 0044
JSONSerializing.swift:14 let obj: AnyObject = toNSJSONSerializationObject()JSONSerializing.swift:23 return jsonArray.map { $0.toNSJSONSerializationObject() }JSONSerializing.swift:27 cocoaDictionary[key] = json.toNSJSONSerializationObject()