我使用以下格式创建了一个具有JSON响应的API:
[{"name":"xxx","direct_link":"http:\/\/domain.com\/images\/xxx.png","image":"http:\/\/domain.com\/images\/xxx.png"},{"name":"yyy","direct_link":"http:\/\/domain.com\/images\/yyy.png","image":"http:\/\/domain.com\/images\/yyy.png"}]
注意JSON响应如何没有数组标题。
我的Swift代码如下所示:
do {
//converting resonse to NSDictionary
var teamJSON: NSDictionary!
teamJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
//getting the JSON array teams from the response
let teams: NSArray = teamJSON["teams"] as! NSArray
//looping through all the json objects in the array teams
for i in 0 ..< teams.count{
//getting the data at each index
let teamId:Int = teams[i]["name"] as! String!
let teamName:String = teams[i]["direct_link"] as! String!
let teamMember:Int = teams[i]["image"] as! Int!
//displaying the data
print("name -> ", teamId)
print("direct_link -> ", teamName)
print("image -> ", teamMember)
print("===================")
print("")
}
注意数组如何寻找标题&#34;团队&#34;。如何确保正确解析JSON并显示JSON响应所需的3个值?我是应用程序编码的新手,并且拥有网络背景,仍在努力解决这个问题。
当我尝试构建并运行时,我遇到以下错误:fatal error unexpectedly found nil while unwrapping an optional value
答案 0 :(得分:1)
问题在于这一行:
teamJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
因为您正在尝试将JSON数组转换为字典。
只需使用
teamJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray
然后你也不需要这样做:
//getting the JSON array teams from the response
let teams: NSArray = teamJSON["teams"] as! NSArray
因为teamJSON已经是数组。
我认为您必须注意的关键问题是NSJSONSerialization.JSONObjectWithData()
可以返回NSDictionary或NSArray,具体取决于JSON中的根级别数据是数组还是字典。
答案 1 :(得分:1)
试试这个:
do {
guard let teams = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray else {
//Doesn't exist, or isn't an NSArray
return
}
for team in teams {
//getting the data at each index
let teamId = team["name"] as! String
let teamName = team["direct_link"] as! String
let teamMember = team["image"] as! Int
//displaying the data
print("name -> ", teamId)
print("direct_link -> ", teamName)
print("image -> ", teamMember)
print("===================")
print()
}
}
//...
一些注意事项:
String!
)guard let
强制执行前提条件(例如,JSON
不是nil,可以转换为NSArray
)。for team in teams
)迭代数组元素(for i in 0..<teams.count
)
for i in teams.indices
for (index, team) in teams.enumerate()
答案 2 :(得分:0)
<强> ISSUE:强>
您的NSJSONSerialization.JSONObjectWithData
会返回NSArray
而非NSDictionary
解决方案:
更新代码如下:
var teamJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray
//getting the JSON array teams from the response
let teams: NSArray = teamJSON
同时强>
请勿使用 !
始终使用?