SwiftyJSON Reading JSON Array issue

1.1k Views Asked by At

I'm trying to read a json array data as below with my code but I'm getting empty result all the time while I can print the whole data. Please where would be my issue?

I've read this topic but I couldn't get the result. Topic Link

{"Cars":[{"Brand":"Alfa Romeo"},{"Brand":"Audi"},{"Brand":"BMW"},{"Brand":"Citroen"},{"Brand":"Dacia"},{"Brand":"Fiat"},..........

My code

    func getData(){

    var url = "http://test.net/services/test.php"
    var request = HTTPTask()
    request.GET(url, parameters: nil, completionHandler:
        {
            (response:HTTPResponse) in

            var jsonData = response.responseObject as! NSData
            var json = JSON(data: jsonData)

            println("All data \(json)")

            dispatch_async(dispatch_get_main_queue(),
                {
                    println(json["Cars"]["Brand"].stringValue)
            })
    })
}
2

There are 2 best solutions below

1
On BEST ANSWER

json["Cars"] is an array, so for example to get the first item via SwiftyJSON:

println(json["Cars"][0]["Brand"].stringValue)

In a JSON string, { and } are delimiters for dictionaries, whereas [ and ] are delimiters for arrays.

EDIT:

Following your comment, yes, you can loop over the array:

if let cars = json["Cars"].array {
    for car in cars {
        println(car["Brand"])
    }
}
0
On

This way you can get your json objects using SwiftyJSON:

//Get your Data First
let json = JSON(data: data)

//Store your values from car key into Car object so we can get total count.
let Cars = json["Cars"].arrayValue

//Use For loop to get your car Brand 
for i in 0..<Cars.count
{
    println(json["Cars"][i]["Brand"].stringValue)
}

And your output will be:

Alfa Romeo
Audi
BMW
Citroen
Dacia
Fiat

Hope this is what you need.