json - 从 JSON、Swift3 访问对象属性

标签 json swift swift3

    let url = URL(string: "http://192.168.30.243:5000/trippy/destination/info?id=4864cc0a-8")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print ("ERROR")
        }
        else {
            if let content = data {
                do {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(myJson)

                    if let information = myJson as? NSDictionary { 
                        print (information.value(forKey: "EmergencyNumbers")!)
                        if let number = information.value(forKey: "EmergencyNumbers") as? NSArray {

 //This is the part I am unsure about

                            if let description = number[0] as? AnyObject {
                               //I know do not know how to access the object's attribute values

                            }
                        }
                    }
                }
                catch {

                }
            }
        }
    }
    task.resume()

}

我已经使用 JSON 来解析来自网络的数据。我使用字典来访问信息,然后使用数组从特定键获取数据。在这个数组中有一些对象。我如何访问每个对象的属性值?

JSON 示例:

{
    Currency = testCurrency;
    DestinationId = "4864cc0a-8";
    DialCode = testDialCode;
    DoesntUseMetricSystem = 0;
    DrinkingAge = 16;
    DriverLicense = 1;
    EmergencyNumbers =     (
                {
            Description = "Emergency Pizza Delivery";
            Id = 1;
            Number = 6969;
        }
    );
    Id = 1;
    IsNorthHemisphere = 1;
    OfficialLanguage =     {
        Id = 1;
        Name = testLanguage;
    };
    PowerGridVoltage = 226;
    PowerSocket = dk;
    Telecoms = nonern;
    Tipping = 2;
    WidelySpokenLanguages =     (
                {
            Id = 2;
            Name = testtLanguage;
        }
    );
    WrongSideOfRoad = 0;
}

最佳答案

我看到你来自 Objective-C 世界,所以首先我建议你放弃使用 NSArray , NSDictionary等支持他们的 Swift 同行 Array Dictionary :

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
  ...
  let JSON = try? JSONSerialization.jsonObject(with: data!, options: [])
  if let dictionary = JSON as? [String: Any], 
     let emergencyNumbers = dictionary["EmergencyNumbers"] as? [[String: Any]]
  {
    emergencyNumbers.forEach { numbers in
      print(numbers["Description"] as? String)
      print(numbers["Id"] as? Int)
      print(numbers["Number"] as? Int)
    }
  }
}

顺便说一句[String: Any]只是 Dictionary<String, Any> 的语法糖.这同样适用于数组:[[String: Any]]用于 Array<Dictionary<String, Any>> .

关于json - 从 JSON、Swift3 访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46748486/

相关文章:

python - 解析 JSON Lines 文件

javascript - 如何循环这个 JSON 字符串?

ios - NSJSONSerializer 如何确定给定数据的编码?

ios - 如何计算得分速度?

ios - 如何修复 AWSCore (AWS-sdk-ios) 中的 [AWSTask 异常] 崩溃

ios - 我的 Times Table 应用程序在 swift 中出错

json - TypeScript 在不公开字段的情况下定义 getter

使用 Hive 解析 json

ios - 无主在逻辑上等同于弱!在 swift

swift - 无法使用类型为 'encode' 的参数列表调用 'NSAttributedString'