在下面的代码中,如何从JSON向模型添加值

时间:2019-07-16 11:00:58

标签: swift model-view-controller tableview alamofire

我有一个UITableview,需要在其中填充JSON中的数据。

我正在使用MVC体系结构。但是我在将值追加到模型时遇到错误

 class DisplayAttendanceModel {
   let name: String?
   let date: String?
   let subject: String?
   let status: String?

   init(name: String, date:String, subject:String, status:String) {
     self.name = name
     self.date = date
     self.subject = subject
     self.status = status
 }
  var arrData = [DisplayAttendanceModel]()
  let headers : HTTPHeaders = ["Authorization":"token" + " " + ProfileAuth]
    let params : [String:Any] = [
        "date":"15/07/2019",
        "course_id":1,
        "batch_id":1,
        "subject_id":1
    ]

   Alamofire.request(displayURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        if((response.result.value) != nil) {
            var jsonVAr = JSON(response.result.value!)
            if let da = jsonVAr["attendence"].arrayObject {
                self.data = da as! [[String:AnyObject]]
                print(self.data)
                for item in self.data {
                    print(item["student__first_name"] ?? "NO")
                    var names = item["student__first_name"]?.stringValue

                    self.arrData.append(DisplayAttendanceModel(name: names ?? "", date: names ?? "", subject: names ?? "", status: names ?? ""))

                }

我的JSON响应是:

 "attendence": [
        { 
            "attendance_time": "15:35:34.787322",
             "student__last_name": "acharya",
             "student__first_name": "mahendra",
             "subject__name": "Physiology",
             "attendance_date": "2019-07-15",
             "status": 1
         }

如何将这些值附加到模型类,将不胜感激。

3 个答案:

答案 0 :(得分:4)

您应该这样创建模型:

模型

class Attendence: Codable {
    var attendence: [DisplayAttendanceModel]?
}

class DisplayAttendanceModel: Codable {
    let firstName: String?
    let lastName: String?
    let date: String?
    let time: String?
    let subject: String?
    let status: Int?

    enum CodingKeys: String, CodingKey {
        case firstName = "student__first_name"
        case lastName = "student__last_name"
        case date = "attendance_date"
        case time = "attendance_time"
        case subject = "subject__name"
        case status
    }
}

然后您可以像这样使用

请求

Alamofire.request(displayURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
    if response.result.value != nil {
        guard let data = response.data { return }

        do { 
            let myData = try JSONDecoder().decode(Attendence.self, from: data)
            print("myData is: \(myData)")
        } catch let error {
            print(error)
            // Do something in error case
        }

我希望这是可行的。

享受。

答案 1 :(得分:2)

您可以尝试

MyObj

Alamofire.request(displayURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseData { (response) in
   guard let data = response.data else { return }

   do {

     let res = try JSONDecoder().decode(Root.self, from:data)

     print(res)
  }
  catch { 
     print(error)
  }
} 

答案 2 :(得分:1)

这种方式无疑会起作用:

    Alamofire.request(displayURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseString { (response) in
                    if let mresponse = response.value {
                        var jsondata : [String : Any] = [:]
                        if let data = mresponse.data(using: String.Encoding.utf8) {
                            do {
                                //json data extracted as a dictionary
                                jsondata = try JSONSerialization.jsonObject(with: data, options: [])  as? [String:Any]
                            } catch {
                                print(error.localizedDescription)
                            }
                        }
                        if let da = jsondata["attendence"] as? [[String : Any]] {

                            for item in da {
                                print(item["student__first_name"] ?? "NO")
                                var names = item["student__first_name"] as! String

                                self.arrData.append(DisplayAttendanceModel(name: names ?? "", date: names ?? "", subject: names ?? "", status: names ?? ""))

                            }
                        }
                    }
                }