While writing a pet project app in Swift I put together this convenience function that simplifies converting an NSData into JSON objects via the NSJSONSerialization class. My JSONObjectWithData function adds a Swift-friendly API on top of the Foundation method of the same name. Here is a Gist showing how it works and how to use it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
/** Outputs of the JSONObjectWithData function. */ | |
enum JSONObjectWithDataResult | |
{ | |
case Success(AnyObject) | |
case Failure(NSError) | |
} | |
/** | |
Attempts to convert the specified NSData to JSON objects | |
and returns either the root JSON object or an error. | |
*/ | |
func JSONObjectWithData( | |
data: NSData, | |
options: NSJSONReadingOptions = nil) | |
-> JSONObjectWithDataResult | |
{ | |
var error: NSError? | |
let json: AnyObject? = | |
NSJSONSerialization.JSONObjectWithData( | |
data, | |
options: options, | |
error: &error) | |
return json != nil | |
? .Success(json!) | |
: .Failure(error ?? NSError()) | |
} | |
// | |
// Example usage | |
// | |
func readSomeJSON() | |
{ | |
// Get JSON data somewhere… | |
let data = NSData() | |
switch JSONObjectWithData(data) | |
{ | |
case .Success(let json): println("json: \(json)") | |
case .Failure(let error): println("error: \(error)") | |
} | |
} |
Pingback: Dew Drop – July 29, 2014 (#1824) | Morning Dew
Pingback: Dew Drop – July 30, 2014 (#1825) | Morning Dew