如何使用 Alamofire 和 SwiftyJSON 正确创建一个类来保存来自 JSON 的数据
Posted
技术标签:
【中文标题】如何使用 Alamofire 和 SwiftyJSON 正确创建一个类来保存来自 JSON 的数据【英文标题】:How to properly create a class to hold data from JSON with Alamofire and SwiftyJSON 【发布时间】:2016-06-16 20:15:44 【问题描述】:我正在尝试创建一个类来保存以 JSON 形式发送的来自 web 服务的数据。这是我从服务器返回的 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"
]
]
]
这是我正在创建的模型类(需要帮助!)
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!)
发出http请求的Alamofire函数:
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)
然后在我的视图控制器中,我需要将列表保存在 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 ???
这就是我卡住的地方,如何循环访问对象以将列表中的数据存储到我的 Show 数组中?
关于如何重构我的代码以实现的任何提示,预期结果是每周每天的分段控件,按下时我会将其用作过滤器以显示适当的信息。
谢谢!!!
【问题讨论】:
仅供参考。使用 NSURLSession 编写网络代码,并自己将数据解析为适当的模型。您不应依赖对模型的检查和反思来为它们分配变量。完全删除 Alamofire 的必要依赖项。 感谢@TheCodingArt 的提示,我会试试的!但是你能告诉我为什么我不应该依赖 Alamofire 来做我的方法吗? 您正在添加一个依赖项作为轻量级包装器,但没有真正的好处/收益/原因。这确实是一种反模式,并且会让人头疼。 再次感谢@TheCodingArt 我会记住这一点的。 【参考方案1】:这可能不是最漂亮的方式,但它会起作用。
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)
【讨论】:
感谢@brl214 在摆弄您的回答后,我确实找到了自己的问题。我喜欢 switch 的想法,但我肯定会将它用于 segcontrol! @acmobile 没问题!很高兴你知道了!【参考方案2】:我通过改变三件事得到了我想要的:
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)
(结果)(结果)
.responseObject .responseArray
(响应:响应)(响应:响应)
【讨论】:
以上是关于如何使用 Alamofire 和 SwiftyJSON 正确创建一个类来保存来自 JSON 的数据的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Alamofire 和 SwiftyJSON 将数据发送到表视图
如何使用 Alamofire 和 SwiftyJSON 正确解析 JSON
如何将 RxSwift 与 AlamoFire 和 SwiftyJSON 一起使用?