I have done a webservice to retrieve JSON of data which is as follows:
(this is stored in a variable data)
{"0":{"categoryId":"1","category":"Restaurants"},"1":{"categoryId":"2","category":"Attractions"},"type":"1006","status":"OK"}
However I am unable to successfully retrieve each object as I want to store them into an array dynamically, example
var categoryIDArray = ["1", "2"];
var categoryArray = ["Restaurants", "Attractions"];
therefore I initially wanted to do the following logic as I have done something like this in 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
//}
However I am already stuck in retrieving the number of JSON in swift 2.
//I tried doing the following to see if I am able to retrieve data 0 JSON but it failed
//print(data![0]);
The following codes work, however it is only able to extracts single data
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")
}
Any tips? Thanks!
{"type": "1006", "status": "OK", "data": [{"categoryId": "1", "category": "Restaurants"}, {"categoryId": "2", "category": "Attractions"}]}[[String: Any]]and be able to loop.