如何将此数据解析为swift3并显示到UILabel中。
请有人帮我解决这个问题,因为我刚接触了我的第一个项目。提前谢谢。
{
“Driver_Details” :[
{
“Staff_ID”:2,
“Staff_Name”:”Pratyush”,
“Student_ID”:1
“Route_Number”:”1A”
“Route_Name”:”Guindy”
“Stop_Name”:”Velachery”
“Distance_from_School”:3,
}
]
}
答案 0 :(得分:0)
试试这个。如果你打开这个作为DriverDetails.json的Documents文件夹中的本地文件,你可以试试这个:
if let path = Bundle.main.path(forResource: "DriverDetails", ofType: "json") {
do {
let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
if let json = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: Any] {
if let jsonDriverDetails = json["Driver_Details"] as? [[String: Any]] {
// Here you have an array of DriverDetails Dictionaries
for jsonDriverDetail in jsonDriverDetails {
// Iterating through each Dictionary you can access the values using the key
staffNameLabel.text = jsonDriverDetails["Staff_Name"] as? String
}
}
}
} catch { print(error.localizedDescription) }
}