Created
May 9, 2016 18:53
-
-
Save JohannMG/6958af840b14c9bd9e0f4804eb6c48aa to your computer and use it in GitHub Desktop.
More organized way to collect JSON-parsed variables. Similar to JAVA's BSON where you file it into an object.
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
//: Playground - noun: a place where people can play | |
/** | |
More organized way to collect JSON-parsed variables. | |
Similar to JAVA's GSON where you file it into an object with known types and methods. | |
Best to run it in a SwiftPlayground | |
*/ | |
import Foundation | |
let originalJSONString = "{\"id\":234789,\"State\":\"California\",\"ArrayEx\":[\"element1\",\"element2\"]}" | |
/** | |
{ | |
"id": "234789", | |
"State": "California", | |
"ArrayEx": ["element1", "element2"] | |
} | |
*/ | |
struct SampleJsonConstruct{ | |
let id: Int! | |
let state: String! | |
let missing: String? | |
let elementStrings: [String]! | |
init(fromDictionary dictionary: [String: AnyObject]){ | |
id = dictionary["id"] as! Int | |
state = dictionary["State"] as? String! | |
missing = dictionary["missing"] as! String? ?? "ThisSideIsNil" | |
elementStrings = dictionary["ArrayEx"] as? [String]! | |
} | |
} | |
let data = originalJSONString.dataUsingEncoding(NSUTF8StringEncoding) | |
let resultDict = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] | |
let done = SampleJsonConstruct(fromDictionary: resultDict) | |
done.id | |
done.state | |
done.elementStrings | |
done.missing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment