Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterating through a JSON response #32

Closed
Isuru-Nanayakkara opened this issue Aug 1, 2014 · 2 comments
Closed

Iterating through a JSON response #32

Isuru-Nanayakkara opened this issue Aug 1, 2014 · 2 comments

Comments

@Isuru-Nanayakkara
Copy link

I get a JSON response from a web service which looks like this.

{
  "1":"Rooms",
  "2":"Kitchen",
  "3":"Bed1",
  "4":"Bed2",
  "5":"Bed3",
  "6":"Master",
  "7":"Breakfast",
  "8":"Bath1",
  "9":"Bath2",
  "10":"Living"
}

As you can see it's a list of rooms. Each room has a number and a name. I have created a model class called Room with two properties for ID and Name.

Here is the method I call the web service to get the response.

public func getRooms(completionHandler: (response: [Room]?, error: NSError?) -> Void) {
    let response = {(response: NSHTTPURLResponse!, data: HTTPHandler.Data!, error: NSError!) -> Void in
        let json = JSONValue(data)
        println(json["rooms"])

    }
    let httphandler = HTTPHandler.get("http://webservie.com/rooms", response: response)
}

I want to return an array of Room class objects. I get the JSON response to the json constant properly. How can I iterate through it and collect the objects into an array? I tried to do a for in loop on it but apparently its not possible.

Can someone please help me out?

Thank you.

@bsvingen
Copy link

bsvingen commented Aug 1, 2014

Assuming that json contains the JSONValue resulting from your JSON, you can use the object method to turn it into a dictionary that can be iterated:

if let dictionary = json.object {

    for (key, value) in dictionary {

        println("key: \(key), value: \(value)")

    }

}

You can then turn this into an array in any way you choose (or just keep it as a dictionary).

@Isuru-Nanayakkara
Copy link
Author

I got it working like this.

let json = JSONValue(data)

switch json["rooms"] {
case .JObject(let rooms):
    var roomsAray = [Room]()
    for room in rooms {
        var roomObj = Room(id: room.0.toInt(), type: room.1.string)
        roomsAray.append(roomObj)
    }
    completionHandler(response: roomsAray, error: error)
default:
    println("JSON data is broken!")
}

but your way is much cleaner and clearer. Thanks. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants