如何从swift中的Any类型访问我的json数据?

时间:2018-03-16 15:57:40

标签: json swift alamofire

我正在使用Alamofire执行网络通话。响应的返回(下面的调用)返回一个ANY类型。如何访问我的字典数组?

Almofire文档:

 Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)

if let json = response.result.value {
    print("JSON: \(json)")
   }
}

我尝试了以下内容:

let json2 = json as! [[String:String]]

JSON:

 (
    (
            {
        docURL = "https://httpbin.org/get/rab1Mpub.pdf";
        name = "rab1Mpub.pdf";
    }
),
    (
            {
        docURL = "https://httpbin.org/get/1Mpublic.pdf";
        name = "1Mpublic.pdf";
    }
),
    (
            {
        docURL = "https://httpbin.org/get/plantLabBook";
        name = "plantLabBook_1.pdf";
    }
)
)

我刚收到以下错误:

 Could not cast value of type '__NSArrayI' (0x10740c648) to 'NSDictionary' (0x10740b1a8).
2018-03-16 15:46:16.501012+0000 labbook[12637:401862] Could not cast value of type '__NSArrayI' (0x10740c648) to 'NSDictionary' (0x10740b1a8).

1 个答案:

答案 0 :(得分:1)

你有一个数组的数组:

let json = json as! [[[String:String]]]

for outer in json {
    for inner in outer {
        for (key, value) in inner {
            print(key, "has", value)
        }
    }
}

注意:只有在您完全确定对象类型时才应执行as!。即API始终发送[[[String:String]]]

PS:当我需要使用嵌套结构时,我个人使用SwiftyJSON让我的生活更轻松。