使用循环将多个json对象存储到数组中

时间:2017-02-02 15:13:58

标签: arrays json swift2

我已经完成了一个Web服务来检索数据的JSON,如下所示:

(这存储在可变数据中)

{"0":{"categoryId":"1","category":"Restaurants"},"1":{"categoryId":"2","category":"Attractions"},"type":"1006","status":"OK"}

但是我无法成功检索每个对象,因为我想将它们动态存储到数组中,例如

var categoryIDArray = ["1", "2"];
var categoryArray   = ["Restaurants", "Attractions"];

因此我最初想要做以下逻辑,因为我已经在android studio for java& cordova for javascript

//try 
//{
//    for(var i = 0; i < data.count(); i++)
//    {
//        categoryIDArray[i] = data[i].categoryId;
//        categoryArray[i]   = data[i].category;
//    }
//}
//catch(Exception ex)
//{
//    //Catch null pointer or wrong format for json
//}

但是我已经陷入了在swift 2中检索JSON数量的问题。

//I tried doing the following to see if I am able to retrieve data 0 JSON but it failed
//print(data![0]);

以下代码有效,但只能提取单个数据

do{
    let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
    let test1 = (json!["status"] as? String)!
    let test2 = (json!["0"] as? String)!

    print(test1) //shows "OK" 
    print(test2) //shows nil instead of {"categoryId":"1","category":"Restaurants"}

} catch {
    print("JSON parse error")
}

任何提示?谢谢!

2 个答案:

答案 0 :(得分:1)

让我们来看看这句话:

let test1 = (json!["status"] as? Int)!

JSON!意思是:取对象json,打开它,如果它是零则崩溃。

json![&#34; status&#34;]表示:尝试使用&#34; status&#34;作为对象json中的索引。如果json不是字典,这将崩溃。

json![&#34; status&#34;]为? Int表示:获取json的结果![&#34; status&#34;]并尝试将其转换为Int,如果失败则生成nil。

(json![&#34; status&#34;] as?Int)!意思是:从前一行获取可选的int,打开它,如果它是nil则崩溃。

在一行代码中有四个可能的崩溃。

答案 1 :(得分:0)

请试试这个。我确定它正在工作

var arrCatNumber : [String]? = []
var arrCatName : [String]? = []
let data = ["0":["categoryId":"1","category":"Restaurants"],"1":["categoryId":"2","category":"Attractions"],"type":"1006","status":"OK"]
//here data is assumed your json data


for index in 0...data.count - 3{ 
 //data.count = 4 means 5 times lopping and we need actually first for 2 than we minus 3.
 //If data["2"],data["3"] come in response than work fine no need any extra implementation  

    let strIndex = String(index)

    if let test1 = data[strIndex] as? [String : String]{
        arrCatNumber?.append(test1["categoryId"]!)
        arrCatName?.append(test1["category"]!)
    }
}