iOS智能家居App开发:如何将JSON转换为结构体数组?
Got it, let's get your JSON data converted into that struct array for your smart home iOS app! Swift's Codable protocol is exactly what you need here—it makes JSON parsing straightforward and type-safe. Here's how to adjust your code step by step:
1. 修正你的数据结构体
First, let's fix your cellData struct to follow Swift conventions and support Codable. Since your JSON uses keys like namea and statea but your struct uses nameLabel and stateLabel, we'll use a CodingKeys enum to map them properly. Also, avoid using implicit unwrapped optionals (!) unless you're 100% sure the values will always exist (which they do in your sample JSON, so we can use non-optional strings):
// 遵循Codable,首字母大写符合Swift命名规范 struct CellData: Codable { let nameLabel: String let stateLabel: String // 映射JSON的key到结构体属性 enum CodingKeys: String, CodingKey { case nameLabel = "namea" case stateLabel = "statea" } }
2. 解析JSON数据
Next, we'll take your JSON string, convert it to Data, then use JSONDecoder to turn it into an array of CellData. We'll handle potential parsing errors with a do-catch block:
// 你的JSON字符串 let jsonString = """ [{"namea":"TV","statea":"up_tv"},{"namea":"test","statea":"test"}] """ // 转成Data guard let jsonData = jsonString.data(using: .utf8) else { print("Failed to convert JSON string to data") return } // 解码成CellData数组 do { array = try JSONDecoder().decode([CellData].self, from: jsonData) // 解析成功后刷新表格 tableView.reloadData() } catch { print("Error parsing JSON: \(error.localizedDescription)") }
3. 更新你的ViewController代码
Now replace the hardcoded array in your viewDidLoad with the parsing code above. Here's the full updated Main view controller:
class Main: UITableViewController { // 数组类型改成修正后的CellData var array = [CellData]() override func viewDidLoad() { super.viewDidLoad() // 解析JSON数据 let jsonString = """ [{"namea":"TV","statea":"up_tv"},{"namea":"test","statea":"test"}] """ guard let jsonData = jsonString.data(using: .utf8) else { print("Failed to convert JSON string to data") return } do { array = try JSONDecoder().decode([CellData].self, from: jsonData) tableView.reloadData() } catch { print("Error parsing JSON: \(error.localizedDescription)") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell cell.nameLabel.text = array[indexPath.row].nameLabel // 注意你原来的代码里拼写错误:stateLabal → stateLabel cell.stateLabel.text = array[indexPath.row].stateLabel return cell } }
小提示:
- 我注意到你原来的代码里有个拼写错误:
stateLabal→ 应该是stateLabel,已经在上面的代码里修正了,不然会导致标签不显示内容。 - 如果你的JSON是从网络请求来的,只需要把
jsonData换成网络请求返回的Data即可,解析逻辑是一样的。
内容的提问来源于stack exchange,提问作者SimonLovskog

