3

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!

7
  • Why does the webservice make a dictionary with integers as keys instead of having an array? This is not good JSON format... Commented Feb 2, 2017 at 15:54
  • @EricAya Hi , possible to advice on a good json format? I am able to make the changes for now Commented Feb 2, 2017 at 17:07
  • I would use an array for the dictionaries, something like that: {"type": "1006", "status": "OK", "data": [{"categoryId": "1", "category": "Restaurants"}, {"categoryId": "2", "category": "Attractions"}]} Commented Feb 2, 2017 at 17:17
  • You would then cast the result of json["data"] to an array of dictionaries: [[String: Any]] and be able to loop. Commented Feb 2, 2017 at 17:19
  • @EricAya: It's actually not a legal format. Dictionary keys in JSON must be strings. Commented Feb 2, 2017 at 19:05

2 Answers 2

1

Let's examine this statement:

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

json! means: Take the object json, unwrap it, and crash if it is nil.

json!["status"] means: Try to use "status" as an index in the object json. This will crash if json is not a dictionary.

json!["status"] as? Int means: Take the result of json!["status"] and try to convert it to Int, producing nil if this fails.

(json!["status"] as? Int)! means: Take the optional int from the previous line, unwrap it, and crash if it is nil.

That's about four possible crashes in a single line of code.

Sign up to request clarification or add additional context in comments.

Comments

0

Please try this. i sure it's working

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"]!)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.