我是iOS Swift的新手。在这里,我有一个jsonResponse,它来自我的Web服务。现在,我想解析此响应到我的数组。这是我的模型类代码。
struct OrderItem:Codable{
let purchaseId : Int
let purchasedDate: String
let purchasedStatus: Int
let purchasedItems: [String]
}
这是我来自网络服务的回复。
URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error)-> Void in
do{
// let data = try JSONSerialization.jsonObject(with: data!, options: []) as! Array<Any>
let decoder = JSONDecoder()
self.orderMenu = try! decoder.decode([OrderItem].self, from: data!)
print("===122===",self.orderMenu)
}catch{
print("ERROR")
}
DispatchQueue.main.async {
self.MytableView.reloadData()
}
}).resume()
这是我的jsonResponse
[
{
"purchaseId": 19,
"purchasedDate": "2018-07-27 23:48",
"purchasedStatus": 0,
"purchasedItems": [
{
"purchasedItemsId": 72,
"purchasedCount": 2,
"purchasedPrice": 34,
"purchasedGST": 3,
"itemDescription": "abcd2",
"itemCategoryDescription": "Cloths_Type_6",
},
{
"purchasedItemsId": 73,
"purchasedCount": 3,
"purchasedPrice": 44,
"purchasedGST": 9.1,
"itemDescription": "Item2",
"itemCategoryDescription": "Flags",
},
{
"purchasedItemsId": 74,
"purchasedCount": 4,
"purchasedPrice": 123,
"purchasedGST": 3,
"itemDescription": "Item3",
"itemCategoryDescription": "Food",
},
{
"purchasedItemsId": 75,
"purchasedCount": 5,
"purchasedPrice": 42,
"purchasedGST": 9.1,
"itemDescription": "Item4",
"itemCategoryDescription": "Flags",
}
]
}
]
有人请给我一个解决方案,任何解决方案表示赞赏。
答案 0 :(得分:0)
purchasedItems
是一个字典数组,对于字典,您必须创建另一个结构
struct OrderItem : Decodable {
let purchaseId : Int
let purchasedDate: String
let purchasedStatus: Int
let purchasedItems: [PurchasedItem]
}
struct PurchasedItem : Decodable {
let purchasedItemsId, purchasedCount, purchasedPrice : Int
let purchasedGST : Double
let itemDescription, itemCategoryDescription : String
}
然后您可以使用
打印itemDescription
中的orderMenu
for order in orderMenu {
for item in order.purchasedItems {
print(item.itemDescription)
}
}
然后-再次-始终在catch
块中打印错误实例
} catch {
print(error)
}