I have been grappling with JSON for a couple of days and realised I am making a basic error. When I have a JSON file like below my code just below it works perfectly:
{"team": [
{
"name": "Manchester United FC",
"code": "MUFC"
},
{
"name": "Swansea City",
"code": "SWA"
}
]
}
Code that works with above JSON file:
func jsonParsing()
{
let path: NSString = NSBundle.mainBundle().pathForResource("teams", ofType: "json")!
var data : NSData = NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMapped, error: nil)!
var dict: NSDictionary!=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
for var i = 0 ; i < (dict.valueForKey("team") as NSArray).count ; i++
{
arrDict.addObject((dict.valueForKey("team") as NSArray) .objectAtIndex(i))
}
}
However, when my JSON file does not have quote marks for the titles as per below it causes a "fatal error: unexpectedly found nil while unwrapping an Optional value" issue:
{team: [
{
name: "Manchester United FC",
code: "MUFC"
},
{
name: "Swansea City",
code: "SWA"
}
]
}
So, you may ask why don't I simply use quotes so it works? Well, I am getting the JSON information from a website so have to use that format. For full details on the original file format checkout:
http://api.football-data.org/alpha/soccerseasons/354/teams
So, is there a simple setting I can use so it uses my JSON file without the need for all the double quotes?
Many thanks in advance, Alan.
Those quotes are must for JSON to work. http://www.w3schools.com/json/json_syntax.asp
The following seems to work:
{
//let path: NSString = NSBundle.mainBundle().pathForResource("teams", ofType: "json")!
//var data : NSData = NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMapped, error: nil)!
let url2 = NSURL(string: "http://api.football-data.org/alpha/soccerseasons/354/teams")
let data = NSData(contentsOfURL: url2!)
var dict = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary
// var dict: NSDictionary!=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
for var i = 0 ; i < (dict.valueForKey("teams") as NSArray).count ; i++
{
arrDict.addObject((dict.valueForKey("teams") as NSArray) .objectAtIndex(i))
}
}
But now I am even more confused as everyone says the original file is not vaild :/ Thoughts anyone?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.