相关疑难解决方法(0)

正确解析Swift 3中的JSON

我正在尝试获取JSON响应并将结果存储在变量中.我已经在Swift的早期版本中使用了此代码的版本,直到GM版本的Xcode 8发布.我看了一下StackOverflow上的一些类似的帖子:Swift 2解析JSON - 无法下标Swift 3中的'AnyObject'JSON解析类型的值.

但是,似乎那里传达的想法并不适用于这种情况.

如何在Swift 3中正确解析JSON响应?在Swift 3中读取JSON的方式有什么变化吗?

以下是有问题的代码(可以在游乐场中运行):

import Cocoa

let url = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"

if let url = NSURL(string: url) {
    if let data = try? Data(contentsOf: url as URL) {
        do {
            let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)

        //Store response in NSDictionary for easy access
        let dict = parsedData as? NSDictionary

        let currentConditions = "\(dict!["currently"]!)"

        //This produces an error, Type 'Any' has no subscript members …
Run Code Online (Sandbox Code Playgroud)

parsing json swift swift3 xcode8

118
推荐指数
5
解决办法
12万
查看次数

标签 统计

json ×1

parsing ×1

swift ×1

swift3 ×1

xcode8 ×1