我有一个json对象日:
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”] ]
}
我希望每天都能获得一个列表,并将可用小时数作为字符串。
["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 ]
我正在使用此函数来处理数据,我每天都会传递JSON对象:
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)
}
问题是我无法通过任何一天,因为它不能转换为[[String]]
答案 0 :(得分:1)
这对我有用:
// 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 ""
}
您必须通过使用密钥传递JSON来调用该函数。
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")