Parsing JSON files is easy as long as you remember that all the Data is of type AnyObject and that you can try to cast the fields to String or Int as needed. An array is of type [AnyObject], a dictionary of type [String: AnyObject], a string of type String and an integer of type Int.
We will write some code to parse this very simple JSON file:
{
"people": [ "bob", "rob"]
}
The code to parse this is:
brush: swift
func parseJSON(data: NSData?) {
do {
if let data = data, response = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue:0)) as? [String: AnyObject] {
// people is an array
if let array: AnyObject = response["people"] {
for person in array as! [AnyObject] {
if let name = person as? String {
// Do something with the name
postNameInObscureBlog(name)
} else {
print("Not a string")
}
}
}
else {
print("people key not found in dictionary")
}
}
else {
print("JSON Error")
}
} catch let error as NSError {
print("Error parsing results: \(error.localizedDescription)")
}
}