Ehab Saifan
Ehab Saifan

Reputation: 589

Swift: JSON object of two dimensional array processing

I have a json object days:

days = {"available_hours":{ 
    "Monday" : [ ["5:30 am","11:00 am"] , [“1:00 pm","4:00 pm”], ["4:00 pm”,  "9:00 pm"] ]
    "Tuesday" : [ [“2:30 pm","7:50 pm"] ]
    "Friday" : [ [“7:30 am","12:50 pm"], [“4:00 pm","11:59 pm”] ]
}  

and I want to get a list with each day and the available hours as a string.

 ["Monday 5:30 am - 11:00 am, 1:00 pm - 4:00 pm, 4:00 pm - 9:00 pm”, "Tuesday 2:30 pm","7:50 pm",etc ]

I am using this function to precess the data and I am passing each day JSON object:

private func hoursList(shifts: [[String]]) -> String{
    var shiftslist: [String] = []
    var shifttext: String = ""
    for shift in shifts {
        shifttext += "\(shifts[0]) - \(shift[1])"
        shiftslist.append(shifttext)
    }  
    return join(", ", shiftslist)
}

the problem is that I cant pass any day because its not convertible to [[String]]

Upvotes: 1

Views: 1361

Answers (1)

Karlos
Karlos

Reputation: 1661

This worked for me:

   // Int from JSON
func getIntFromJSON(data: NSDictionary, key: String) -> Int {

    let info : AnyObject? = data[key]

    if let info = data[key] as? Int {
        return info
    }

    else {
        return 0

    }

}

// Array from JSON
func getArrayFromJSON(data: NSDictionary, key: String) -> NSArray {

    let info : AnyObject? = data[key]

    if let info = data[key] as? NSArray {
        return info
    }

    else {
        return []

    }

}
//Object from JSON
func getObjectFromJSON(data: NSDictionary, key: String) -> AnyObject {

    let info : AnyObject? = data[key]

    if let info: AnyObject = data[key] {
        return info
    }

    else {
        return []

    }

}
// String from JSON
func getStringFromJSON(data: NSDictionary, key: String) -> String {

    let info : AnyObject? = data[key]
    println(data[key])
    if let info = data[key] as? String {
        return info
    }

    return ""
}

You have to call the function by passing your JSON with the key .

    var available_hours = self.getArrayFromJSON(JSONString as! NSDictionary, key: "available_hours")

    // Passing available_hours to get the values for sub-array
    var Tuesday = self.getStringFromJSON(available_hours as! NSDictionary, key: "Tuesday")

Upvotes: 1

Related Questions