如何在Swift 2中访问JSON数组的元素

时间:2016-07-14 11:47:20

标签: swift

我有一个字符串dataString,其中包含以下json信息:

{"products":[
 {"DBID":"2954","ScanID":"143","Name":"Cables","Count": 7,"Info":""},
 {"DBID":"5551","ScanID":"129","Name":"Batteries","Count": 24,"Info":""},
 {"DBID":"7143","ScanID":"003","Name":"Media","Count": 49,"Info":""}
]}

我怎么能

  1. 使用Swift 2迭代这些数据来计算所有产品的“计数”字段总数?
  2. 访问特定“产品”广告位的数据元素。例如,如果我知道我需要在插槽1中检索产品的“名称”,我该如何直接访问它?

1 个答案:

答案 0 :(得分:0)

要获得所有计数的总和,您可以使用iOS的sum运算符。如需更多收集操作员,请查看此link。您需要像这样更改代码

do {
    //Here jsonStr in your json String
    let data = jsonStr.dataUsingEncoding(NSUTF8StringEncoding)
    let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
    let proArr = dic["products"] as! NSArray
    let sum = proArr.valueForKeyPath("@sum.Count")
    print(sum) //Print sum of the all count
    print(proArr[0]["name"]) //To print name of first products
}
catch let e as NSError {
    print(e.localizedDescription)
}