sau123
sau123

Reputation: 352

iterate JSON, swift

I am working on swift. The response that I get from the web server is different when i test it on Postman/ browser and mobile emulator.

Postman/browser response :

items: [
    {
    itemId: 500,
    name: "ABC"
    },
    {
    itemId: 500,
    name: "ABC"
    }
    ]

Response in iOS :

 items: (
    {
    itemId: 500,
    name: "ABC"
    },
    {
    itemId: 500,
    name: "ABC"
    }
    )

I would like to know how to iterate through the array, but since the result is not an array on iOS I am not sure on how should I go about it. Also, I retrieve a result of around 25-30 items in the array. I have a some set of variables too, that are provided in the response after the array.

Upvotes: 2

Views: 3066

Answers (3)

Nirav D
Nirav D

Reputation: 72420

There is no problem with your response in ios when you print an array it will print with () brackets instead of [] brackets and dictionary will be print with {} braces.

As you say let items : [NSDictionary]! your items array contain dictionary then you can iterate it like this

for item in items {
    print(item["itemId"])
    print(item["name"])
}

Upvotes: 3

Natasha
Natasha

Reputation: 6893

You have an array of dictionaries. So, you can iterate like-

for itemDict in items {
    let itemId = itemDict["itemId"]
    println("Item ID: \(itemId)")

    let name = itemDict["name"]
    println("Item name: \(name)")
}

Upvotes: 0

Wyetro
Wyetro

Reputation: 8588

As others have said, your response in iOS is fine.

You can iterate over it simply with:

for item in items {

// do what you want with each item

}

It works fine in a Playground:

let items = [["itemId": 500, "name" : "ABC"], [ "itemId": 500, "name": "ABC"]] as NSArray


for item in items {
    print(item as! NSDictionary) // prints each dictionary as expected
}

Upvotes: 0

Related Questions