我试图通过WCF服务从sql server获取数据

时间:2018-05-20 11:58:12

标签: ios swift nsurlsession codable

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   与键CodingKeys相关联的值(stringValue:\" id \",intValue:   nil)(\" id \")。",underlyingError:nil))

1 个答案:

答案 0 :(得分:0)

嗯,打印出的错误非常自我解释。您获得的数据没有按照您期望的方式格式化,并且缺少某些键(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()            
    }
}