【问题标题】:JSON Complex Arrays in SwiftSwift 中的 JSON 复杂数组
【发布时间】:2015-01-01 22:34:05
【问题描述】:

有没有办法在 Swift 中实现这一点?

var z = [ //Error 1
    {
        "Name":{ //Error 2
            "First":"Tika",
            "Last":"Pahadi"
        },
        "City":"Berlin",
        "Country":"Germany"
    }
]

var c:String = z[0]["Name"]["First"] as String //Error 3 

我收到一堆错误,例如:

  1. 无法将表达式的类型 Array 转换为 ArrayLiteralConvertible
  2. 连续的元素必须用分号隔开
  3. 类型“Int”不符合协议“StringLiteralConvertible”

【问题讨论】:

    标签: ios arrays json swift swift-playground


    【解决方案1】:

    如果您在 Swift 中表示此结构,请对字典和数组使用方括号。并且不要忘记打开可选项:

    let z = [
        [
            "Name":[
                "First":"Tika",
                "Last":"Pahadi"
            ],
            "City":"Berlin",
            "Country":"Germany"
        ]
    ]
    
    if let name = z[0]["Name"] as? [String: String], let firstName = name["First"] {
        // use firstName here
    }
    

    但是,假设您确实收到了该 JSON 是由于某个网络请求与URLSession 的结果。然后你可以用JSONSerialization解析它:

    do {
        if let object = try JSONSerialization.jsonObject(with: data) as? [[String: Any]],
            let name = object[0]["Name"] as? [String: String],
            let firstName = name["First"] {
                print(firstName)
        }
    } catch {
        print(error)
    }
    

    或者更好,在 Swift 4 中,我们会使用 JSONDecoder

    struct Name: Codable {
        let first: String
        let last: String
    
        enum CodingKeys: String, CodingKey {  // mapping between JSON key names and our properties is needed if they're not the same (in this case, the capitalization is different)
            case first = "First"
            case last = "Last"
        }
    }
    
    struct Person: Codable {
        let name: Name
        let city: String
        let country: String
    
        enum CodingKeys: String, CodingKey {  // ditto
            case name = "Name"
            case city = "City"
            case country = "Country"
        }
    }
    
    do {
        let people = try JSONDecoder().decode([Person].self, from: data)   // parse array of `Person` objects
        print(people)
    } catch {
        print(error)
    }
    

    【讨论】:

      【解决方案2】:

      Swift 无法猜测您的 JSON 数组中有哪些类型。它无法猜测你的数据是一个数组,它无法猜测第一个数组元素是一个字典,它无法猜测键“Name”下的值是一个字典。实际上,您不知道它们是因为您无法控制服务器向您发送的内容。

      那么当 NSJSONSerialization 返回一个 AnyObject 时呢?您需要将其转换为 NSArray*(最好进行一些检查,否则如果它不是 NSArray,您的应用程序将崩溃),检查数组中是否有任何对象,将第一个元素转换为 NSDictionary*(再次检查如果它不是 NSDictionary*) 等,则避免崩溃。

      【讨论】:

      • "您需要将其转换为 NSArray" ... 或转换为 Swift 数组。 ;)
      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      相关资源
      最近更新 更多