json - 在 Swift 3 中正确解析 JSON

我正在尝试获取 JSON 响应并将结果存储在变量中。在 Xcode 8 的 GM 版本发布之前,我已经在以前的 Swift 版本中使用了此代码的版本。我在 StackOverflow 上看了一些类似的帖子:Swift 2 Parsing JSON - Cannot subscript a value of type 'AnyObject'和 JSON Parsing in Swift 3 .

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

如何正确解析 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
        let currentTemperatureF = ("\(dict!["currently"]!["temperature"]!!)" as NSString).doubleValue

            //Display all current conditions from API
            print(currentConditions)

            //Output the current temperature in Fahrenheit
            print(currentTemperatureF)

        }
        //else throw an error detailing what went wrong
        catch let error as NSError {
            print("Details of JSON parsing error:\n \(error)")
        }
    }
}

编辑:以下是 print(currentConditions) 之后 API 调用的结果示例
["icon": partly-cloudy-night, "precipProbability": 0, "pressure": 1015.39, "humidity": 0.75, "precipIntensity": 0, "windSpeed": 6.04, "summary": Partly Cloudy, "ozone": 321.13, "temperature": 49.45, "dewPoint": 41.75, "apparentTemperature": 47, "windBearing": 332, "cloudCover": 0.28, "time": 1480846460]

最佳答案

首先永远不要从远程 URL 同步加载数据 , 始终使用异步方法,如 URLSession .

'Any' has no subscript members



发生是因为编译器不知道中间对象是什么类型(例如 currently 中的 ["currently"]!["temperature"] )并且因为您使用的是 Foundation 集合类型,例如 NSDictionary编译器根本不知道类型。

此外,在 Swift 3 中,需要通知编译器有关 的类型。全部 下标对象。

您必须将 JSON 序列化的结果转换为实际类型。

此代码使用 URLSession独家 Swift 原生类型
let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
  if error != nil {
    print(error)
  } else {
    do {

      let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
      let currentConditions = parsedData["currently"] as! [String:Any]

      print(currentConditions)

      let currentTemperatureF = currentConditions["temperature"] as! Double
      print(currentTemperatureF)
    } catch let error as NSError {
      print(error)
    }
  }

}.resume()

打印 currentConditions 的所有键/值对你可以写
 let currentConditions = parsedData["currently"] as! [String:Any]

  for (key, value) in currentConditions {
    print("\(key) - \(value) ")
  }

关于 jsonObject(with data 的说明:

许多(似乎都是)教程建议 .mutableContainers.mutableLeaves选项在 Swift 中完全是无稽之谈。这两个选项是传统的 Objective-C 选项,用于将结果分配给 NSMutable...对象。在 Swift 中,任何 var默认情况下,iable 是可变的,并传递任何这些选项并将结果分配给 let常数根本没有影响。此外,大多数实现无论如何都不会改变反序列化的 JSON。

唯一(罕见)在 Swift 中有用的选项是 .allowFragments如果 JSON 根对象可以是值类型( StringNumberBoolnull )而不是集合类型之一( arraydictionary ),则这是必需的。但通常省略options参数,表示无选项。

================================================== ==========================

解析 JSON 的一些一般注意事项

JSON 是一种排列整齐的文本格式。读取 JSON 字符串非常容易。 仔细阅读字符串 .只有六种不同的类型——两种集合类型和四种值类型。

集合类型是
  • 数组 - JSON:方括号中的对象 [] - swift :[Any]但在大多数情况下 [[String:Any]]
  • 字典 - JSON:花括号中的对象 {} - swift :[String:Any]

  • 值类型是
  • 字符串 - JSON:双引号中的任何值 "Foo" ,甚至 "123""false" – swift :String
  • 数字 - JSON:数值 不是 双引号 123123.0 – swift :IntDouble
  • bool 值 - JSON:truefalse 不是 双引号 - Swift:truefalse
  • null - JSON:null – swift :NSNull

  • 根据 JSON 规范,字典中的所有键都必须是 String .

    基本上总是建议使用可选绑定(bind)来安全地解包可选值

    如果根对象是字典( {} ),则将类型强制转换为 [String:Any]
    if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] { ...
    

    并通过键检索值( OneOfSupportedJSONTypes 是 JSON 集合或值类型,如上所述。)
    if let foo = parsedData["foo"] as? OneOfSupportedJSONTypes {
        print(foo)
    } 
    

    如果根对象是数组( [] ),则将类型强制转换为 [[String:Any]]
    if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] { ...
    

    并遍历数组
    for item in parsedData {
        print(item)
    }
    

    如果您需要特定索引处的项目,请检查该索引是否存在
    if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]], parsedData.count > 2,
       let item = parsedData[2] as? OneOfSupportedJSONTypes {
          print(item)
        }
    }
    

    在极少数情况下,JSON 只是值类型之一——而不是集合类型——你必须传递 .allowFragments选项并将结果转换为适当的值类型,例如
    if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String { ...
    

    Apple 在 Swift 博客中发表了一篇综合文章:Working with JSON in Swift

    ================================================== ==========================

    在 Swift 4+ 中 Codable协议(protocol)提供了一种更方便的方法来将 JSON 直接解析为结构/类。

    例如问题中给定的 JSON 示例(略有修改)
    let jsonString = """
    {"icon": "partly-cloudy-night", "precipProbability": 0, "pressure": 1015.39, "humidity": 0.75, "precip_intensity": 0, "wind_speed": 6.04, "summary": "Partly Cloudy", "ozone": 321.13, "temperature": 49.45, "dew_point": 41.75, "apparent_temperature": 47, "wind_bearing": 332, "cloud_cover": 0.28, "time": 1480846460}
    """
    

    可以解码成结构Weather . Swift 类型与上述相同。还有一些额外的选项:
  • 表示 URL 的字符串可以直接解码为URL .
  • time整数可以解码为 DatedateDecodingStrategy .secondsSince1970 .
  • 可以使用 keyDecodingStrategy 将snaked_cased JSON key 转换为camelCase .convertFromSnakeCase

  • struct Weather: Decodable {
        let icon, summary: String
        let pressure: Double, humidity, windSpeed : Double
        let ozone, temperature, dewPoint, cloudCover: Double
        let precipProbability, precipIntensity, apparentTemperature, windBearing : Int
        let time: Date
    }
    
    let data = Data(jsonString.utf8)
    do {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .secondsSince1970
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let result = try decoder.decode(Weather.self, from: data)
        print(result)
    } catch {
        print(error)
    }
    

    其他可编码来源:
  • Apple: Encoding and Decoding Custom Types
  • HackingWithSwift: Codable Cheat Sheet
  • Ray Wenderlich: Encoding and Decoding in Swift
  • https://stackoverflow.com/questions/39423367/

    相关文章:

    mysql - 在 MySQL 中以 JSON 格式存储数据

    c# - 使用 JSON.NET 的序列化字段的顺序

    javascript - 如何动态创建 JavaScript 数组(JSON 格式)?

    json - REST API - 文件(即图像)处理 - 最佳实践

    c# - JSON.net:如何在不使用默认构造函数的情况下反序列化?

    ios - 如何在 Swift 中解析来自 Alamofire API 的 JSON 响应?

    c# - 如何在 C# 中将字典转换为 JSON 字符串?

    android - 如何使用 Android 通过 Request 发送 JSON 对象?

    arrays - YAML 等效于 JSON 中的对象数组

    javascript - 从浏览器下载 JSON 对象作为文件