我的数据格式
{
"StationID": "1001",
"StationName": {
"Zh_tw": "基隆",
"En": "Keelung"
},
"TrainNo": "1281",
"Direction": 1,
"TrainClassificationID": "1131",
"TripLine": 0,
"EndingStationID": "1025",
"EndingStationName": {
"Zh_tw": "新竹",
"En": "Hsinchu"
},
"ScheduledArrivalTime": "22:02:00",
"ScheduledDepartureTime": "22:04:00",
"DelayTime": 0,
"Platform": "",
"SrcUpdateTime": "2017-01-24T22:14:29+08:00",
"UpdateTime": "2017-01-24T22:14:40+08:00"
},
我的代码(Swift 3)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
// Configure the cell...
cell.stationID.text = trainStatusArray[indexPath.row]["StationID"] as? String
let stationDirect = trainStatusArray[indexPath.row]["Direction"] as? Int
if stationDirect == 0 {
cell.stationdirection.text = "順行"
}else{
cell.stationdirection.text = "逆行"
}
cell.stationtrainNo.text = trainStatusArray[indexPath.row]["TrainNo"] as? String
let stationTripline = trainStatusArray[indexPath.row]["TripLine"] as? Int
if stationTripline == 0 {
cell.stationtripLine.text = "不經山線/海線"
}else if stationTripline == 1 {
cell.stationtripLine.text = "山線"
}else {
cell.stationtripLine.text = "海線"
}
//cell.stationtripLine.text = String(stationTripline!)
return cell
}
我的问题是如何将StationName,Zh_tw和En传输到TableView单元格?
答案 0 :(得分:0)
StationName
和EndingStationName
都是字典,因此您可以像这样获得Zh_tw
的价值。
if let stationName = trainStatusArray[indexPath.row]["StationName"] as? [String:Any],
let zhTW = stationName ["Zh_tw"] as? String, let en = stationName ["En"] as? String {
cell.stationName.text = zhTW
}else {
cell.stationName.text = ""//Set default name
}
同样适用于EndingStationName
。
注意:如果您从此词典创建自定义对象数组,则可以通过cellForRowAt
方法轻松分配标签文本,而不是使用字典数组。
答案 1 :(得分:0)
首先将JSON String
转换为Data
,然后使用Data
再次将Dictionary
转换为JSONSerialization
表单
Swift 3
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
// pass your String JSON
let dict = convertToDictionary(text: str)
Swift 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
从String获取dictonary
let dict= convertStringToDictionary(str)
if let strStationName= result?["EndingStationName"] {
let zhTW = strStationName["Zh_tw"] as? String
cell.stationdirection.text=zhTW
}