我已经从API调用接收的JSON对象中解析了数据。到目前为止,我可以在调试器控制台中打印JSON数据,但是我试图将解析的JSON转换回可以在UI中显示的数据。我有两个模型,一个JSON对象的示例如下所示:
{
"query": "milk",
"sort": "relevance",
"responseGroup": "base",
"totalResults": 693,
"start": 1,
"numItems": 10,
"items": [{
"itemId": 10291863,
"parentItemId": 10291863,
"name": "Carnation Vitamin D Added Evaporated Milk, 12 oz",
"msrp": 1.79,
"salePrice": 1.48
}]
}
我只想显示详细说明
name
和salePrice
键的信息。但是,由于JSON是嵌套的,所以我不知道如何到达该层以检索值。这是我的数据模型代码:struct Item: Codable {
let query: String
let sort: String
let responseGroup: String
let totalResults: Int
let start: Int
let numItems = 25
let items: [Product]
}
struct Product: Codable {
let name: String
let salePrice: Double
}
代码到我的ViewController中:
class ViewController: UIViewController {
@IBOutlet weak var itemField: UITextField!
@IBAction func filterButton(_ sender: Any) {
var components = URLComponents()
components.scheme = "http"
components.host = "api.walmartlabs.com"
components.path = "/v1/search"
let queryItemKey = URLQueryItem(name: "apiKey", value: secretKey)
var queryItemQuery = URLQueryItem(name: "query", value: itemField.text)
components.queryItems = [queryItemKey, queryItemQuery]
let searchURL = components.url
//Task to make API Network Call
guard let url = components.url else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
//Implement JSON decoding and parsing
do {
//Decode retrived data with JSONDecoder and assing type of Item object
let productData = try JSONDecoder().decode(Item.self, from: data)
print(productData)
} catch let jsonError {
print(jsonError)
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
运行代码时,打印日志显示以下内容(再次,我只想显示
name
和salePrice
值。是否可以将这些值放置在数组中或以某种方式转换这些值?用我的用户界面填充? 最佳答案
创建一个数据源数组
var products = [Product]()
解析数据后,将products数组分配给数据源数组并重新加载表视图
...
let productData = try JSONDecoder().decode(Item.self, from: data)
self.products = productData.items
DispatchQueue.main.async {
self.tableView.reloadData()
}
在
numberOfRowsInSection
中返回products.count
在
cellForRow
中获取当前产品并将值分配给标签let product = products[indexPath.row]
cell.textLabel!.text = product.name
cell.detailTextLabel!.text = "\(product.salePrice)"
关于arrays - 如何在UI中显示已解析的JSON数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49488739/