【问题标题】:Accessing Object Attributes from JSON, Swift3从 JSON、Swift3 访问对象属性
【发布时间】:2017-10-14 19:25:37
【问题描述】:
    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;
}

【问题讨论】:

标签: json swift swift3


【解决方案1】:

我知道你来自 Objective-C 世界,所以首先我建议你放弃使用 NSArrayNSDictionary 等,转而使用 Swift 对应的 ArrayDictionary

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>>

【讨论】:

  • 记住 NS 意味着不是 Swift ;)
【解决方案2】:

一如既往,不要在 Swift 中使用 NSArray / NSDictionary。你扔掉类型信息。

根对象是一个字典 ([String:Any]),键 EmergencyNumbers 的值是一个数组 ([[String:Any]])。使用循环遍历数组。

if let root = try JSONSerialization.jsonObject(with: content) as? [String:Any] {
    print(myJson)

    if let emergencyNumbers = root["EmergencyNumbers"] as? [[String:Any]] {
        for emergencyNumber in emergencyNumbers {
            let description = emergencyNumber["Description"] as? String
            let id = emergencyNumber["Id"] as? Int
            let number = emergencyNumber["Number"] as? Int

            print("description", description ?? "n/a")
            print("id", id ?? "n/a")
            print("number", number ?? "n/a")
        }
}

其他一些坏习惯:

  • .mutableContainers 在 Swift 中完全没有意义。有趣的是,每个通过选项 .mutableContainers 的人都会将结果分配给一个不可变的常量。
  • Swift 3+ 中未指定的 JSON 类型是 Any 而不是 AnyObject
  • valueForKey,一种KVC方式,不适合这个目的,使用objectForKey或者key订阅。对于 Swift 原生类型,根本不用它。

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2014-01-21
    相关资源
    最近更新 更多