2017-05-25 90 views
-2

我有一个服务器响应返回Swift3我如何获取字符串中特定键的值?

(
    { 
    agreementId = "token.virtual.4321"; 
    city = AMSTERDAM; 
    displayCommonName = "bunch-of-alphanumeric"; 
    displaySoftwareVersion = "qb2/ene/2.7.14"; 
    houseNumber = 22; 
    postalCode = zip; 
    street = ""; 
    } 
) 

我怎么AGREEMENTID的价值?响应['agreementId']不起作用。我已经用.first尝试了一些示例代码,但是我无法正常工作。

一些额外的信息,我做了一个http调用alamofire服务器。我尝试了JSON解析到一个固定的响应:

let response = JSON as! NSDictionary 

但是返回一个错误信息

Could not cast value of type '__NSSingleObjectArrayI' (0x1083600) to 'NSDictionary' (0x108386c). 

所以,现在的JSON解析到一个数组,这似乎是工作。上面的代码是

let response = JSON as! NSArry 
print(response) 

吐出来。

现在我只需要检索key“agreementId”的值,我不知道该怎么做。

+0

什么是“响应”,是通过解析json检索的字典?调试你的代码并检查“响应”*实际*是什么。 – luk2302

+0

变量JSON是什么类型? – Spads

回答

2

在SWIFT你需要使用Swift的原生型Array/[]Dictionary/[:]代替NSArrayNSDictionary,如果指定的类型像上面意味着更具体的那么编译器不会抱怨。还可以使用可选包装if letguard let来防止崩溃。

if let array = JSON as? [[String:Any]] {//Swift type array of dictionary 
    if let dic = array.first { 
     let agreementId = dic["agreementId"] as? String ?? "N/A"//Set default value instead N/A 
     print(agreementId) 
     //access the other key-value same way 
    } 
} 

注:如果您有您的阵列中的多个对象,那么你需要简单地遍历数组访问阵列的每个字典。

if let array = JSON as? [[String:Any]] {//Swift type array of dictionary 
    for dic in array { 
     let agreementId = dic["agreementId"] as? String ?? "N/A"//Set default value instead N/A 
     print(agreementId) 
     //access the other key-value same way 
    } 
} 
+1

谢谢!这是解决方案。并感谢其他的指针,帮助我很多作为swift newb –

+0

@JeroenSwets欢迎队友:) –

相关问题