我正在制作一个框架。我想使用Codable
协议转换服务器响应JSON。但它有[String:Any]
价值。如何清除错误? Type 'Person' does not conform to protocol 'Encodable'
public class Person: Codable {
public var name: String?
public var age: Int?
public var userOriginalData: [String:Any]? // [String:Any]? or data? or Row JSON string
}
答案 0 :(得分:-1)
嗨请检查我的答案我没有收到任何错误。
import UIKit
struct Website : Decodable {
let name : String
let description : String
let courses : [Course]
}
struct Course : Decodable {
let id : Int?
let name : String?
let link : String?
let imageUrl : String?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
getStartedBtn.setTitle(GetStarted, for: .normal)
// Do any additional setup after loading the view, typically from a nib.
self.callAPI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func callAPI(){
let urlString = "https://api.letsbuildthatapp.com/jsondecodable/website_description"
guard let url = URL.init(string: urlString) else {
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
return
}
do {
let web = try JSONDecoder().decode(Website.self, from: data)
print(web.courses[0])
}
catch let error {
print("error",error)
}
}.resume()
}
}