import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var hero = [HeroStruct]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
navigationController?.navigationBar.barTintColor = UIColor.systemYellow
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemYellow ]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: nil)
cell.textLabel?.text = ""
cell.backgroundColor = .systemYellow
return cell
}
func getJsonData(completion: @escaping () -> () ) {
let url = URL(string: "https://api.opendota.com/api/heroStats")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
if error != nil {
print(error?.localizedDescription)
}else {
do {
let result = try JSONDecoder().decode(HeroStruct.Type, from: data!)
}catch {
print(error)
}
}
}
}
}
import Foundation
struct HeroStruct : Decodable {
let localized_name : String
let primary_attr : String
let attack_type : String
let legs : Int
let img : String
}
第一個代碼塊是我的 ViewController.swift 頁面,
第二個代碼塊是我的 HeroStruct.swift 頁面,
我試圖從 Json 獲取資料,但出現如下錯誤:
型別 'HeroStruct.Type' 不能符合 'Decodable'
我該如何解決這個問題?
let result = try JSONDecoder().decode([HeroStruct].Type, from: data!)`
我試過這樣寫,但沒有用。需要幫助,謝謝。
uj5u.com熱心網友回復:
替換[HeroStruct].Type為[HeroStruct].self。每當您想解碼某些內容時,請始終使用.self& not .Type。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534971.html
標籤:JSON迅速类型可解码
下一篇:組件在小部件內部的互動性如何?
