gpt4 book ai didi

JSON - Swift 中的模型 + 实现

转载 作者:行者123 更新时间:2023-11-28 09:01:39 24 4
gpt4 key购买 nike

我看过很多关于在 Swift 中解析 JSON 的视频,但我就是不明白。我正在尝试以正确的方式获取它,这意味着异步方式,所以我不会阻止任何东西。我只是对数组中的字典中的字典中的数组等 JSON 结构感到非常困惑,我不知道如何正确解析它。

我想了解如何使用 Struct 或 Class 作为单独的文件为我的应用程序建模,创建它的实例并在 UTTableView 中解析 JSON。

让我感到困惑的是,我不知道如何构建所有内容(模型 + 实现)。

例如,我一直在研究这个 JSON http://api.football-data.org/alpha/teams/66/fixtures

我想用那个团队的固定装置制作一个模型,所以制作一个模型,实现/解析 JSON 并填充 Tableview。

到目前为止我的代码示例:

在我的模型(这是一个结构)中我有这个:

  struct RestApiManager {

var awayTeamName: NSString
var homeTeamName: String

var dateOfTheMatch: NSDate
var leagueRound: Int

// var goalsHomeTeam: Int
// var goalsAwayTeam: Int
//
// var clubIcons: String


init(fixturesDictionary: NSDictionary) {

let allFixtures = fixturesDictionary["fixtures"] as! NSArray

awayTeamName = fixturesDictionary["awayTeamName"] as! NSString
homeTeamName = fixturesDictionary["homeTeamName"] as! String
dateOfTheMatch = fixturesDictionary["date"] as! NSDate
leagueRound = fixturesDictionary["matchday"] as! Int


}

在 Viewcontroller 我有这个(因为我只是在测试 JSON,如果它正确返回数据,那么它不会 - 它崩溃并且错误显示“ fatal error :意外发现展开可选值时为零”,我不知道为什么):

let fixturesUrl = NSURL(string: "http://api.football-data.org/alpha/teams/66/fixtures")

let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(fixturesUrl!) { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

// If there's no errors then unwrap the optional values
if (error == nil) {

// Creates a data object based on the information of the "location"
let dataObject = NSData(contentsOfURL: location) // "location" is the file that's stored on the disk

// Convert the dataObject into a JSON object
let fixturesDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary

// Instance of RestApiManager

let restApiManager = RestApiManager(fixturesDictionary: fixturesDictionary)

println(restApiManager.dateOfTheMatch)

}

}

downloadTask.resume()

如果有人能告诉我如何做,我将不胜感激。

最佳答案

JSON 数据不能包含 NSDate 对象。它包含:NSDictionary、NSArray、NSString、NSNumber(用于数字和 bool 值)和 NSNull。您必须查看收到的数据以了解服务器使用何种格式向您报告日期,并添加代码以将字符串转换为日期。

除此之外,我真的希望您意识到,每当 JSON 数据与您使用 as 时的预期不匹配时! ,您的应用程序将崩溃。因为那是什么!意思是:“请帮我转换它,如果它不起作用,请崩溃”。

关于JSON - Swift 中的模型 + 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31872362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com