问题描述
我需要解析此JSON的帮助
{
"products_and_categories" : {
"new" : [
{
"id" : 173577,"image_url" : "\/\/assets.supremenewyork.com\/193786\/ca\/tMUMOnomKJI.jpg","name" : "Penguins Hooded Fleece Jacket","price" : 19800,"sale_price" : 0,"image_url_hi" : "\/\/assets.supremenewyork.com\/193786\/rc\/tMUMOnomKJI.jpg","new_item" : true,"position" : 4,"category_name" : "Jackets"
},{
"id" : 173581,"image_url" : "\/\/assets.supremenewyork.com\/193727\/ca\/ywdDy1mQ51Q.jpg","name" : "Side logo Track Jacket ","price" : 15800,"image_url_hi" : "\/\/assets.supremenewyork.com\/193727\/rc\/ywdDy1mQ51Q.jpg","position" : 3,"category_name" : "Jackets"
}
]
}
}
我已经制作了这个结构来保存已解析的值
var modelsArray: [Products] = Array() //is Products the right one for the array?
struct Products: Codable {
let products: Categories
enum CodingKeys: String,CodingKey {
case products = "products_and_categories"
}
}
struct Categories: Codable {
let new: [New]
}
struct New: Codable {
let id: Int
let name: String
let price: Int
let category: String
let image: String
enum CodingKeys: String,CodingKey {
case id
case name,price
case category = "category_name"
case image = "image_url_hi"
}
}
let url = URL(string: "https://www.supremenewyork.com/shop.json")!
let request = URLRequest(url: url)
let session = URLSession.shared
session.dataTask(with: request) { (data,response,error) in
if data = data {
// Having trouble with what to put here to append id,name,price,category,image for tableview
}
}.resume()
但是现在我被困住了,我无法将其转换为请求以追加我需要的数据。本质上,我希望能够将ID,名称,价格,类别,图像放入表格视图单元格中
解决方法
正如我可能假设的那样,您必须使用new
array
将数据加载到tableView
中。因此,您需要定义自己的modelsArray
,
var modelsArray: [New] = Array()
然后像这样解析JSON data
,
session.dataTask(with: request) { (data,response,error) in
if let data = data {
do {
let response = try JSONDecoder().decode(Products.self,from: data)
modelsArray = response.products.new
//reload your tableView here...
} catch {
print(error)
}
}
}.resume()