gpt4 book ai didi

ios - Swift 解析 JSON 格式

转载 作者:搜寻专家 更新时间:2023-11-01 07:21:02 25 4
gpt4 key购买 nike

我创建了一个具有以下格式的 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("")

}

注意数组如何查找标题“teams”。如何确保 JSON 得到正确解析并显示 JSON 响应所需的 3 个值?我是应用程序编码的新手并且有网络背景,仍在努力解决这个问题。

当我尝试构建和运行时出现以下错误:展开可选值时意外发现 fatal error nil

最佳答案

试试这个:

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()
}
}
//...

一些注意事项:

  1. 不要强制转换为隐式展开的可选值(例如 String! )
  2. 不要添加不必要的类型注释
  3. 使用guard let强制执行先决条件(例如 JSON 不为零,并且可转换为 NSArray )。
  4. 优先遍历数组元素 ( for team in teams ) 而不是遍历范围 ( for i in 0..<teams.count )
    • 如果您只需要索引,请使用 for i in teams.indices
    • 如果您需要索引和元素,请使用 for (index, team) in teams.enumerate()

关于ios - Swift 解析 JSON 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39024917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com