Skip to content

Instantly share code, notes, and snippets.

@JohannMG
Created May 9, 2016 18:53
Show Gist options
  • Save JohannMG/6958af840b14c9bd9e0f4804eb6c48aa to your computer and use it in GitHub Desktop.
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.
//: 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