如何使用Alamofire和SwiftyJSON正确创建一个用于保存JSON数据的类

时间:2022-09-16 19:34:06

I'm trying to create a class to hold data from webservice sent as JSON. Here is the JSON I'm getting back from the server:

我正在尝试创建一个类来保存来自作为JSON发送的webservice的数据。这是我从服务器回来的JSON:

[  
  {  
    "weekSchedule":[  
      {  
        "weekDay":"sunday",
        "listening":[  
          {  
            "textName":"Programa de teste 1",
            "textPresenter":"Apresentador",
            "timeStartHour":"08:00:00",
            "timeEndHour":"23:59:00",
            "textDescription":"Descri\u00e7\u00e3o do programa ",
            "textGuest":"Dr. Lair Ribeiro",
            "urlImage":"file:\/\/servidor\/lampp\/webservice\/img\/happy.png"
          },
          {  
            "textName":"Teste 2",
            "textPresenter":"Teste",
            "timeStartHour":"00:00:00",
            "timeEndHour":"00:00:00",
            "textDescription":"",
            "textGuest":"",
            "urlImage":"file:\/\/servidor\/lampp\/webservice\/img\/happy.png"
          }
        ]
      },
      {  
        "weekDay":"monday",
        "listening":[  
          {  
            "textName":"Programa de teste 1",
            "textPresenter":"Apresentador",
            "timeStartHour":"08:00:00",
            "timeEndHour":"23:59:00",
            "textDescription":"Descri\u00e7\u00e3o do programa ",
            "textGuest":"Dr. Lair Ribeiro",
            "urlImage":"file:\/\/servidor\/lampp\/webservice\/img\/happy.png"
          },
          {  
            "textName":"Programa teste marco",
            "textPresenter":"Marco",
            "timeStartHour":"08:30:00",
            "timeEndHour":"09:30:00",
            "textDescription":"Apenas um programa para testar o json",
            "textGuest":"Jason",
            "urlImage":"file:\/\/servidor-ubuntu\/lampp\/webservice\/img\/happy.png"
          }
        ]
      }
    ]
  }
]

Here are the model classes I'm creating (Need help here!)

以下是我正在创建的模型类(需要帮助!)

import Foundation
import SwiftyJSON

class Show: ResponseJSONObjectSerializable {

  var name: String?
  var description: String?
  var host: String?
  var guest: String?
  var startTime: String?
  var endTime: String?
  var urlImage: String?

  required init(json: JSON) {
    self.name = json["textName"].string
    self.description = json["textDescription"].string
    self.host = json["textPresenter"].string
    self.guest = json["textGuest"].string
    self.startTime = json["timeStartHour"].string
    self.endTime = json["timeEndHour"].string
    self.urlImage = json["urlImage"].string
  }

  required init() {}
}

class ShowArray: ResponseJSONObjectSerializable {

  var weekday: String?
  var showArray: [Show]?

  required init?(json: JSON) {

    self.weekday = json["weekDay"].string

    if let jsonArray = json["listening"].array {
      self.showArray = []

      for json in jsonArray {
        let instance = Show(json: json)
        self.showArray?.append(instance)
      }
    }
  }

}

class ScheduleArray: ResponseJSONObjectSerializable {

  var scheduleArray: [ShowArray]?

  required init?(json: JSON) {

    if let weekArray = json["weekSchedule"].array {
      self.scheduleArray = []

      for weekDay in weekArray {
        let instance = ShowArray(json: weekDay)
        self.scheduleArray?.append(instance!)
      }
    }
  }
}

The Alamofire function to make the http request:

Alamofire函数发出http请求:

func getWeeklyShedule(completionHandler: (Result<ScheduleArray, NSError>) -> Void) {

    alamofireManager.request(RCAppRouter.GetSchedule()).responseObject {
      (response: Response<ScheduleArray, NSError>) in

      guard response.result.isSuccess else {
        print("Error fetching schedule: \(response.result.error!)")
        return
      }

      completionHandler(response.result)
    }
  }

Then in my view controller I need to hold the listings on an array of Show

然后在我的视图控制器中,我需要在Show数组上保存列表

var listings = [Show]()
RCAPIManager.sharedInstance.getWeeklyShedule {
      (result) in

      guard result.error == nil else {
        print("Error")
        return
      }

      guard let fetchedSchedule = result.value else {
        print("No schedule fetched")
        return
      }

      self.listings = fetchedSchedule.scheduleArray ???

    }

This is where I got stuck, how can I loop through the object to store the data from listings to my array of Show?

这就是我陷入困境的地方,我怎样才能遍历对象以将数据从列表存储到我的Show数组中?

Any tips on how to refactor my code to achieve, The expected result is a segmented control for each day o the week, when pressed I'll use it as a filter to display the appropriated information.

关于如何重构我的代码以实现的任何提示,预期的结果是每周的每一天的分段控件,当按下时我将使用它作为过滤器来显示适当的信息。

Thanks!!!

2 个解决方案

#1


1  

This might not be the prettiest way but it'll work.

这可能不是最漂亮的方式,但它会起作用。

if let responseArray = response as? NSArray {
    for i in 0..<responseArray.count {
    let showDic = responseArray[i] as! NSDictionary
    let dayOfWeek = showDic["weekday"] as! String
    let showArray = showDic["listening"] as! NSArray
        switch dayOfWeek {
        case "sunday":
           addShowObjectsToArray(showArray, dailyShows: sundayArray)
        case "monday":
           addShowObjectsToArray(showArray, dailyShows: mondayArray)
        case "tuesday":
           addShowObjectsToArray(showArray, dailyShows: tuesdayArray)
        case "wednseday":
           addShowObjectsToArray(showArray, dailyShows: wednsedayArray)
        case "thursday":
           addShowObjectsToArray(showArray, dailyShows: thursdayArray)
        case "friday":
           addShowObjectsToArray(showArray, dailyShows: fridayArray)
        case "saturday":
           addShowObjectsToArray(showArray, dailyShows: saturdayArray)
        default:
        }
    }

func addShowObjectsToArray(shows: NSArray, dailyShows: NSArray) {
    for show in shows {
        let showObject = Show(show)
        dailyShows.append(showObject)
    }
}

#2


0  

I got what I wanted by changing three things:

通过改变三件事我得到了我想要的东西:

func getWeeklyShedule(completionHandler: (Result<[ScheduleArray], NSError>) -> Void) {

    alamofireManager.request(RCAppRouter.GetSchedule()).responseArray {
      (response: Response<[ScheduleArray], NSError>) in

      guard response.result.isSuccess else {
        print("Error fetching schedule: \(response.result.error!)")
        return
      }

      completionHandler(response.result)
    }
  }

(Result) <==> (Result<[ScheduleArray], NSError>)

(结果)<==>(结果<[ScheduleArray],NSError>)

.responseObject <==> .responseArray

.responseObject <==> .responseArray

(response: Response) <==> (response: Response<[ScheduleArray], NSError>)

(响应:响应)<==>(响应:响应<[ScheduleArray],NSError>)

#1


1  

This might not be the prettiest way but it'll work.

这可能不是最漂亮的方式,但它会起作用。

if let responseArray = response as? NSArray {
    for i in 0..<responseArray.count {
    let showDic = responseArray[i] as! NSDictionary
    let dayOfWeek = showDic["weekday"] as! String
    let showArray = showDic["listening"] as! NSArray
        switch dayOfWeek {
        case "sunday":
           addShowObjectsToArray(showArray, dailyShows: sundayArray)
        case "monday":
           addShowObjectsToArray(showArray, dailyShows: mondayArray)
        case "tuesday":
           addShowObjectsToArray(showArray, dailyShows: tuesdayArray)
        case "wednseday":
           addShowObjectsToArray(showArray, dailyShows: wednsedayArray)
        case "thursday":
           addShowObjectsToArray(showArray, dailyShows: thursdayArray)
        case "friday":
           addShowObjectsToArray(showArray, dailyShows: fridayArray)
        case "saturday":
           addShowObjectsToArray(showArray, dailyShows: saturdayArray)
        default:
        }
    }

func addShowObjectsToArray(shows: NSArray, dailyShows: NSArray) {
    for show in shows {
        let showObject = Show(show)
        dailyShows.append(showObject)
    }
}

#2


0  

I got what I wanted by changing three things:

通过改变三件事我得到了我想要的东西:

func getWeeklyShedule(completionHandler: (Result<[ScheduleArray], NSError>) -> Void) {

    alamofireManager.request(RCAppRouter.GetSchedule()).responseArray {
      (response: Response<[ScheduleArray], NSError>) in

      guard response.result.isSuccess else {
        print("Error fetching schedule: \(response.result.error!)")
        return
      }

      completionHandler(response.result)
    }
  }

(Result) <==> (Result<[ScheduleArray], NSError>)

(结果)<==>(结果<[ScheduleArray],NSError>)

.responseObject <==> .responseArray

.responseObject <==> .responseArray

(response: Response) <==> (response: Response<[ScheduleArray], NSError>)

(响应:响应)<==>(响应:响应<[ScheduleArray],NSError>)