Skip to content

Instantly share code, notes, and snippets.

@AstroCB
Created September 5, 2016 20:19
Show Gist options
  • Save AstroCB/041f89f5ba223122be41636d06236931 to your computer and use it in GitHub Desktop.
Save AstroCB/041f89f5ba223122be41636d06236931 to your computer and use it in GitHub Desktop.
A snippet that makes working with JSON in Swift a little less painful using JS-like syntax.
/**
Handles JSON in an OO/JavaScript-y fashion
# Example usage
`let json: JSON = JSON(url: "https://me.com/me.json")`
`print(JSON.parse(json.load()))`
*/
public struct JSON {
var url: String
/**
Pulls JSON from the URL provided in the object instantiation
- returns: A `Data` object containing the JSON data if load is successful; `nil` if not
*/
func load() -> Data? {
let urlT: URL = URL(string: url)!
do {
let data = try Data(contentsOf: urlT)
return data
} catch {
print("Error: " + error.localizedDescription)
return nil
}
}
/**
Static method for parsing a JSON Data object into an NSDictionary
- parameter data: A Data object in JSON format (see [JSON formatting docs](http://www.json.org))
- returns: An NSDictionary that can be used to extract data using object:forKey
*/
static func parse(_ data: Data?) -> NSDictionary {
if let inputData: Data = data {
do {
if let JSON: NSDictionary = try JSONSerialization.jsonObject(with: inputData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
return JSON
}
} catch {
print("Parse failed: \((error as NSError).localizedDescription)")
}
} else {
print("Cannot parse invalid data")
}
return NSDictionary()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment