Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/121.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift中的JSON复杂数组_Ios_Arrays_Json_Swift_Swift Playground - Fatal编程技术网

Ios Swift中的JSON复杂数组

Ios Swift中的JSON复杂数组,ios,arrays,json,swift,swift-playground,Ios,Arrays,Json,Swift,Swift Playground,有没有办法在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 //E

有没有办法在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 
我会遇到很多错误,比如:

  • 无法将表达式的类型数组转换为ArrayTerralConvertible
  • 连续元素必须用分号分隔
  • 类型“Int”不符合协议“StringLiteralConverable”

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


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

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


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

    如果要用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
    }
    

    但假设您通过
    URLSession
    的某个网络请求收到了JSON。然后,您可以使用
    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)
    }
    

    如果要用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
    }
    

    但假设您通过
    URLSession
    的某个网络请求收到了JSON。然后,您可以使用
    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)
    }
    

    “您需要将其强制转换为
    NSArray
    ”。。。或发送至Swift阵列。(“您需要将其强制转换为
    NSArray
    ”。。。或发送至Swift阵列。(