我需要帮助解析这个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,
"sale_price" : 0,
"image_url_hi" : "//assets.supremenewyork.com/193727/rc/ywdDy1mQ51Q.jpg",
"new_item" : true,
"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()
然后像这样解析JSONdata
,
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()