Simplifying NSJSONSerialization in Swift

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.


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)")
}
}

view raw

main.swift

hosted with ❤ by GitHub

This entry was posted in Swift and tagged , . Bookmark the permalink.

2 Responses to Simplifying NSJSONSerialization in Swift

  1. Pingback: Dew Drop – July 29, 2014 (#1824) | Morning Dew

  2. Pingback: Dew Drop – July 30, 2014 (#1825) | Morning Dew

Comments are closed.