我想从本地JSON文件解析JSON,并希望将该数据保存在模型类中并在tableview上显示。如何从本地文件解析JSON。
这是我的JSON文件-JsonFile.json
{
"teams":[
{
"teamName":"Arsenal",
"image":"Arsenal",
"nextMatch":"in 2 days",
"matches":[
{
"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"
},
{
"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"
}
],
"fixtures":{
"oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"homeTeamScore":"4",
"homeTeamCards":"True",
"oppositeTeamCards":"false",
"fixtureId":"ID 213432"
}
},
{
"teamName":"Chelsea",
"image":"Chelsea",
"nextMatch":"in 2 days",
"matches":{
"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"
},
"fixtures":{
"oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"homeTeamScore":"4",
"homeTeamCards":"True",
"oppositeTeamCards":"false",
"fixtureId":"ID 213432"
}
},
{
"teamName":"India",
"image":"India",
"nextMatch":"in 2 days"
}
]
}
这是我要存储JSON文件中数据的模型类。
class TeamData : Decodable{
let teamName : String
let image : String
let nextMatch : String?
let matches : [Match]
let fixtures : [Fixture]
}
class Match : Decodable{
let oppositeTeam : String?
let matchTimings : String?
let matchId : String?
}
class Fixture : Decodable{
let oppositeTeam : String?
let oppositeTeamScore : String?
let HomeTeamScore : String?
let HomeTeamCards : String?
let oppositeTeamCards : String?
let fixtureId : String?
}
现在如何解析JSON文件中的数据并将其保存在模型类中。.我看过很多教程,但是每个教程都在使用API,因此,如何从本地文件解析JSON确实令人困惑
答案 0 :(得分:1)
修复TeamData的json结构和类
更改TeamData类以使其与json匹配
class TeamData: Decodable {
var teamName : String
var image : String
var nextMatch : String?
var matches : [Match]?
var fixtures : Fixtures?
}
对于切尔西队,您忘了将比赛安排在阵列上,因此按以下步骤解决问题:
[{
"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"
}]
我认为,最好的办法是,如果您的json文件中仅有的东西是TeamData对象的数组。因此,删除
{ “teams”:
最后和}
并保持一组团队
如何从json文件中获取json
在ViewController中的某个地方创建空的TeamData数组
var teams = [TeamData]()
现在获得对您的json文件的引用,尝试从中创建数据并使用JSONDecoder对此数据进行解码
let url = Bundle.main.url(forResource: "JsonFile", withExtension: "json")!
do {
let data = try Data(contentsOf: url)
teams = JSONDecoder().decode([TeamData].self, from: data)
} catch {
print(error)
}
我还建议您将文件重命名为 Teams.json
也不要忘记在获取文件URL的行中对其重命名