ios - Swift 解析 JSON 格式

标签 ios json swift

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

相关文章:

json - WildFly 中的 jackson-jaxrs 提供程序与 EAR 部署发生冲突

javascript - 如何访问json返回的对象的对象

swift - 无法使用类型为 'CGRect.Type.init' 的参数列表调用 '(x: Int, y: Int, width: Float, height: Float)'

ios - UIScrollView 需要根据 UILabel 大小进行扩展,但保持底部标签栏

java.io.IOException : unexpected end of stream on okhttp3. 地址@e31061fc

iOS调查应用程序

swift - 如何在 Xcode 11/Swift 5.1 中使用 Swift Package Manager 创建动态框架(像 Carthage 那样)?

ios - SWRevealviewcontroller 嵌套 ViewController

iOS 编程 - 日历

iphone - 如何在表格 View 中插入和删除单元格