我尝试从JSON(http://www.openligadb.de/api/getmatchdata/bl1/2014/15)获取数据。我想让每一场比赛都有目标,位置,球队……我尝试过,但无法正常工作。
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
//parse url
if let JSONData = NSData(contentsOfURL: NSURL(string: url)!) {
if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary {
//handle json
}
}
它不会进入第二个if语句(if let json = (try?...
)。我希望你能帮助我。
编辑获取字典的数据:
//Data Team1
if let team1 = object["Team1"] as? NSDictionary {
if let name = team1["TeamName"] as? String {
print("Name Team1: \(name)")
}
if let logo = team1["TeamIconUrl"] as? String {
print("Logo Team1: \(logo)")
}
// Etc.
}
您需要做的是了解JSON结构:首先拥有一个数组,而不是一个字典。
该数组具有字典,每个字典都包含一个字典数组。
听起来可能很复杂,但实际上很简单,您只需遵循JSON的结构,然后使用正确的类型对值进行解码即可。
在JSON中,数组以开头,[
而字典以开头{
(另外,请注意不要将此JSON语法与Swift的数组和字典混淆)。
您的代码可能是这样的,例如:
do {
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
if let url = NSURL(string: url),
JSONData = NSData(contentsOfURL: url),
jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
for object in jsonArray {
if let goalsArray = object["Goals"] as? NSArray {
// Each "goal" is a dictionary
for goal in goalsArray {
print(goal)
if let name = goal["GoalGetterName"] as? String {
print("Name: \(name)")
}
if let ID = goal["GoalID"] as? Int {
print("ID: \(ID)")
}
// Etc.
}
}
}
}
} catch {
print(error)
}
更新:您快要准备好了!但是“ Team1”是字典,而不是数组。:)
解决方法如下:
do {
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
if let url = NSURL(string: url),
JSONData = NSData(contentsOfURL: url),
jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
for object in jsonArray {
if let team1 = object["Team1"] as? NSDictionary {
if let name = team1["TeamName"] as? String {
print("Name Team1: \(name)")
}
if let logo = team1["TeamIconUrl"] as? String {
print("Logo Team1: \(logo)")
}
}
}
}
} catch {
print(error)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句