如何检查SWIFT中填充了json数据的NSArray中是否存在密钥?

时间:2014-06-11 09:49:27

标签: json swift nsjsonserialization

我正在尝试解析这个json响应。

account =     (
            {
            accountName = "Complete Access";
            accountNumber = "062005 1709 5888";
            available = "226.76";
            balance = "246.76";
        }
    );


var account : NSArray = jsonResult.valueForKey("account") as NSArray

现在,此数组包含键“account”的所有值。在这个数组中我们如何检查它是否包含关键的“余额”。我试着检查它如下:

if account .containsObject(account(idx).valueForKey(“balance"))
 {
    transactions.balance = account(idx).valueForKey(“balance”) as? String
 }

但是,它永远不会进入if条件。请指出实现这一目标的正确方法。

1 个答案:

答案 0 :(得分:0)

这样的事情对你有帮助:

let keyAccount: String = "account"
let keyBalance: String = "balance"

var jsonResult : Dictionary<String, AnyObject> = ["account":[["accountName":"Complete Access", "accountNumber":"062005 1709 5888", "available":"226.76", "balance":"246.76"]]]

var account : AnyObject? = jsonResult[keyAccount]
if let accountArray: Array<AnyObject>? = account as? Array {
    if accountArray!.count > 0 {
        if let accountDictionary: Dictionary<String, String>? = accountArray![0] as? Dictionary {
            if let balanceValue: String? = accountDictionary![keyBalance] {
                println("\(balanceValue)")
            }
        }
    }
}