Swift 4中Encodable JSON字典处理方法问询及解决方案分享
在Swift 4中处理指定JSON数据的Encodable字典实现
之前我碰到了在Swift 4里处理这段指定JSON数据并实现Encodable字典转换的问题,多亏@matt的帮忙才顺利解决!现在把完整的实现代码分享出来,给遇到同样需求的开发者做个参考~
原始JSON数据
首先是我们要处理的目标JSON:
{ "restaurants": [ { "id": 1, "restaurantName": "Chuks", "restaurantPicture": "restaurantImages/benards.jpg", "status": "Working", "workingDays": "Tuesday to Sunday", "workingHours": "3pm to 10pm" }, { "id": 3, "restaurantName": "Chuks", "restaurantPicture": "restaurantImages/benards.jpg", "status": "Working", "workingDays": "Tuesday to Sunday", "workingHours": "3pm to 10pm" } ] }
实现Encodable模型
我们需要创建和JSON结构完全匹配的Encodable结构体,Swift 4的Encodable协议可以帮我们自动完成编码逻辑,不需要手动写转换代码:
// 单个餐厅的模型结构体 struct Restaurant: Encodable { let id: Int let restaurantName: String let restaurantPicture: String let status: String let workingDays: String let workingHours: String } // 包含餐厅数组的外层响应结构体 struct RestaurantsResponse: Encodable { let restaurants: [Restaurant] }
转换为字典或JSON数据
1. 将模型转换为字典
如果需要把模型转换成[String: Any]类型的字典,可以通过JSONEncoder先编码成JSON数据,再用JSONSerialization解析成字典:
// 先构造示例模型数据 let restaurant1 = Restaurant(id: 1, restaurantName: "Chuks", restaurantPicture: "restaurantImages/benards.jpg", status: "Working", workingDays: "Tuesday to Sunday", workingHours: "3pm to 10pm") let restaurant2 = Restaurant(id: 3, restaurantName: "Chuks", restaurantPicture: "restaurantImages/benards.jpg", status: "Working", workingDays: "Tuesday to Sunday", workingHours: "3pm to 10pm") let response = RestaurantsResponse(restaurants: [restaurant1, restaurant2]) // 执行转换 do { let jsonData = try JSONEncoder().encode(response) if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] { print("转换完成的字典:\(jsonDict)") } } catch { print("编码失败,错误信息:\(error.localizedDescription)") }
2. 直接获取JSON数据
如果只是需要JSON格式的数据(比如用于网络请求),可以直接使用JSONEncoder的编码结果:
do { let jsonData = try JSONEncoder().encode(response) // 可以将jsonData用于网络请求或者本地存储 if let jsonString = String(data: jsonData, encoding: .utf8) { print("生成的JSON字符串:\(jsonString)") } } catch { print("编码失败,错误信息:\(error.localizedDescription)") }
内容的提问来源于stack exchange,提问作者Sam Banana
相关产品推荐
相关产品推荐

