我尝试通过WCF服务从SQL服务器获取数据


import UIKit
public struct student: Decodable {
let id:Int
let name:String
}
class ViewController: UIViewController {
@IBAction func btnshow(_ sender: Any) {
let link = "http://10.211.55.3/WcfService1/Service1.svc/GetData"
guard let url = URL(string: link)else{
print("error during connection")
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data
else{                    print("there is no data")
return
}
do{
let students = try JSONDecoder().decode(student.self, from: data)
print(students)

} catch{
print("conversion error")
print(error)
}
}.resume()            
}
}

keyNotFound(CodingKeys(stringValue: "id", intValue: nil(, Swift.DecodingError.Context(codingPath: [], debugDescription: "No 与键关联的值 编码键(stringValue: \"id\", intValue: nil( (\"id\"(.", underlyingError: nil((

好吧,打印出来的错误是不言自明的。您获得的数据未按照预期的方式格式化,并且缺少某些键(id键(,因此JSONDecoder()无法对其进行解码。

在尝试解码之前,请确保您收到的响应格式正确。

编辑:所以在看到你的评论后,你的模型与你收到的JSON不匹配,它应该是这样的:

import UIKit
public struct JsonStudent: Decodable {
let students: [Student]
enum CodingKeys: String, CodingKey {
case students = "GetDataResult"
}
}
public struct Student: Decodable {
let id: Int
let name: String
}
class ViewController: UIViewController {
@IBAction func btnshow(_ sender: Any) {
let link = "http://10.211.55.3/WcfService1/Service1.svc/GetData"
guard let url = URL(string: link) else {
print("error during connection")
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data
else {                    print("there is no data")
return
}
do {
let students = try JSONDecoder().decode(JsonStudent.self, from: data)
print(students)
} catch {
print("conversion error")
print(error)
}
}.resume()            
}
}

相关内容

  • 没有找到相关文章

最新更新