简体   繁体   English

尝试将JSON解析为swift3并显示为UILabel

[英]Trying to parse JSON into swift3 and display into UILabel

how to parse this data into swift3 and display into UILabel. 如何将这些数据解析为swift3并显示为UILabel。

please someone help me through this as I'm new to swift and working on my first project. 请有人帮我解决这个问题,因为我是新手,请迅速开始我的第一个项目。 thanks in advance. 提前致谢。

{
    “Driver_Details” :[
   {
        “Staff_ID”:2,
        “Staff_Name”:”Pratyush”,
        “Student_ID”:1
        “Route_Number”:”1A”
        “Route_Name”:”Guindy”
        “Stop_Name”:”Velachery”
        “Distance_from_School”:3,
    }
]
}

Try this. 尝试这个。 If you are opening this as a local file from your Documents folder as DriverDetails.json you can try this: 如果要从“文档”文件夹中将其作为本地文件以DriverDetails.json的形式打开,则可以尝试以下操作:

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) } 
 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM