json - 如何在 Swift 中解析并返回响应中的所有 json 数据?
问题描述
struct LiveScores {
let result: Bool
let data: String
let fixtures: [Fixture]
struct Fixture : Codable {
var kickOffTime: String
var homeTeam: String
var awayTeam: String
}
enum CodingKeys : String, CodingKey {
case homeTeam = "home_name"
case awayTeam = "away_name"
case kickOffTime = "time"
}
}
我正在尝试获取夹具数据,特别是家庭名称、客场名称和时间。以下是我用来获取数据的调用:
func fetchFixtures() {
let session = URLSession.shared
let url = URL(string: "\(baseUrl)fixtures/matches.json?key=\(apiKey)&secret=\(apiSecret)&date=2018-06-01")
let task = session.dataTask(with: url!) { data, response, err in
// check for a hard error
if let error = err {
NSLog("Live Scores Api Error: \(error)")
}
// check the response code
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 200: // perfecto!
if let fixture = self.fixtureFromJSONData(data!) {
NSLog("\(fixture)")
}
case 401: // unauthorised
NSLog("Live Score Api returned an 'unauthorised' response.")
default:
NSLog("Live Scores Api returned response: %d %@", httpResponse.statusCode, HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode))
}
}
}
task.resume()
}
JSON 响应如下所示:
{
"success": true,
"data": {
"fixtures": [
{
"date": "2017-10-16",
"time": "00:30:00",
"round": "999",
"home_name": "Santos Laguna",
"away_name": "Atlas",
"location": "",
"league_id": "88"
},
{
"date": "2017-10-16",
"time": "00:30:00",
"round": "999",
"home_name": "O'Higgins",
"away_name": "Audax Italiano",
"location": "",
"league_id": "63"
},
{
"date": "2017-10-16",
"time": "00:30:00",
"round": "999",
"home_name": "Colorado Rapids",
"away_name": "Real Salt Lake",
"location": "",
"league_id": "94"
}
],
"next_page": "http:\/\/livescore-api.com\/api-client\/fixtures\/matches.json?key=demo_key&secret=demo_secret&page=2",
"prev_page": false
}
我成功解析了数据,但只返回了一个夹具 - 我假设这是因为我指定为“[0]”的索引。
func fixtureFromJSONData(_ data: Data) -> LiveScores.Fixture? {
typealias JSONDict = [String:AnyObject]
let json : JSONDict
do {
json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDict
} catch {
NSLog("JSON parsing failed: \(error)")
return nil
}
var jsonData = json["data"] as! [String:Any]
var fixtureList = jsonData["fixtures"] as! [JSONDict]
var fixtureDict = fixtureList[0]
let fixture = LiveScores.Fixture(
kickOffTime: fixtureDict["time"] as! String,
homeTeam: fixtureDict["home_name"] as! String,
awayTeam: fixtureDict["away_name"] as! String
)
return fixture
}
我如何收到所有归还的灯具的所有主场名称、客场名称和时间?最好的方法是什么?- 我试图改变解析功能,但没有运气。
谢谢 :)
解决方案
如果你使用Codable
不要自己序列化数据,你可以试试
struct LiveScores : Codable
{
let success : Bool
let data: InnerObjc
}
struct InnerObjc: Codable
{
let fixtures: [Fixture]
let nextPage:String
let prevPage:Bool
enum CodingKeys : String, CodingKey {
case fixtures = "fixtures"
case nextPage = "next_page"
case prevPage = "prev_page"
}
}
struct Fixture : Codable {
var kickOffTime: String
var homeTeam: String
var awayTeam: String
enum CodingKeys : String, CodingKey {
case homeTeam = "home_name"
case awayTeam = "away_name"
case kickOffTime = "time"
}
}
//
case 200: // perfecto!
do {
let myResult = try JSONDecoder().decode(LiveScores.self, from: data!)
print(myResult.data.fixtures)
}
catch {
}
推荐阅读
- python - Python 日期时间:格式化字符串 %-m (%#m) 意外行为
- javascript - VanillaJS - 更改事件触发两次
- database - powerapps 表格中的字符太多?无法提交表单
- flutter - Truncate text to a specific digit Flutter Text widget
- javascript - 如何在反应js中有条件地传递数据?
- c++ - 将数组 A 中对应行的所有重复元素复制到新的二维数组 B
- php - php json多维数组输出
- exchangewebservices - EWS OnSubscriptionError 返回错误 - 订阅无效
- javascript - 防止在图像/文件上传后在 create-react-app 中重新加载页面
- javascript - Node.js:对象的数组属性未定义但实际上有值