【问题标题】:how to access array inside json object in swift如何快速访问json对象内的数组
【发布时间】:2017-03-20 15:28:29
【问题描述】:

无法访问 json 对象,它是 json 对象中的数组 我想从数组内有数组的json对象访问数据 并且那个json文件也被上传了 所以请任何人都可以检查并帮助我如何获得“weather.description” 数据

 override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        if error != nil {
            print("some error occured")
        } else {

            if let urlContent =  data {

                do{
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                    let newValue = jsonResult as! NSDictionary

                    print(jsonResult)

                    let name = newValue["name"]
                    //Here i am getting name as variable value

                    //this is not working
                    let description = newValue["weather"]??[0]["description"]

                    //this is not working
                    let description = newValue["weather"]!![0]["description"]

                    print()

                }catch {
                    print("JSON Preocessing failed")
                }

            }
        }
    }
    task.resume()

}

【问题讨论】:

  • 您使用的是哪个 Swift 版本? 3.0?
  • 让我们一块一块地做。 let weatherValue = newValue["weather"] 退货?如果返回正确,let firstWeather = weatherValue[0] 返回?如果返回正确,let weatherDescription = firstWeather["description"] 是否返回?
  • 它不工作它给出错误“类型'Any?'没有下标成员”是可能的,因为我正在将结果转换为 NSDictionary 因为我尝试了大多数选项并且它不起作用并给出了这个错误

标签: ios arrays swift dictionary swift3


【解决方案1】:

我对您的代码进行了一些编辑,并添加了一些 cmets。基本上,让我们检查您的响应结构的类型,并获得所需的值。

let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print("some error occured")
            } else {

                if let urlContent =  data {

                    do{
                        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                        // I would not recommend to use NSDictionary, try using Swift types instead
                        guard let newValue = jsonResult as? [String: Any] else {
                            print("invalid format")
                            return
                        }

                        // Check for the weather parameter as an array of dictionaries and than excess the first array's description
                        if let weather = newValue["weather"] as? [[String: Any]], let description = weather.first?["description"] as? String {
                            print(description)
                        } 

                    }catch {
                        print("JSON Preocessing failed")
                    }
                }
            }
        }
        task.resume()

【讨论】:

  • 它起作用了,还有一件事你能告诉我你为什么使用这种语法 [[String: Any]] 以及为什么我不应该使用 NSDictionary
  • Dictionary ([String: Any]) 是一个原生的 Swift 结构。 NSDictionary 是一个 Cocoa 类。如果您使用的是 Swift,请尝试使用本机 Swift 语言元素!顺便说一句,如果有效,请将其标记为已接受的答案。
  • 我可以有你的电子邮件地址或 Twitter 详细信息
  • let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) if let items = jsonResult["items"] as! NSArray { for item in items { print(item["published"]) print(item["title"]) print(item["content"]) } } 如果我使用此语法,则会给出此错误类型 Any has no subscript member left
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多