如何在带有数字元素的json中检索信息? 我必须迅速在Json中获取信息,但是我有一些数字元素,我不知道如何获取这些部分的信息。
在我的Json中,我设法恢复了一些信息,没有问题。但是那些拥有标题的人不能包含数字,因为例如我不能声明变量“ 1”。我在一天中获得元素标题,但我不知道如何将信息得分排在第一位
Json的网址是:https://www.lnr.fr/flux/rankings?id_competition=prod2
class Classification: Codable {
let channel : Channel
let classification : [Day]
init(channel: Channel ,classification: [Day] ) {
self.channel = channel
self.classification = classification
}
}
class Channel: Codable {
let title: String
init (title: String) {
self.title = title
}
}
class Day: Codable {
let day: day
init(day: day) {
self.day = day
}
}
class day: Codable {
let title: String
let rankings : Equipe
init(title: String, rankings: Equipe) {
self.title = title
self.rankings = rankings
}
}
class Equipe: Codable {
let club: Club
let difference: String
let points: String
let points_marques: String
let points_encaisses: String
let nombre_matchs_joues: String
let nombre_matchs_gagnes: String
let nombre_matchs_nuls: String
let nombre_matchs_perdus: String
init(club: Club,difference: String, points: String, points_marques: String, points_encaisses: String, nombre_matchs_joues: String, nombre_matchs_gagnes: String, nombre_matchs_nuls: String, nombre_matchs_perdus: String) {
self.club = club
self.difference = difference
self.points = points
self.points_marques = points_marques
self.points_encaisses = points_encaisses
self.nombre_matchs_joues = nombre_matchs_joues
self.nombre_matchs_gagnes = nombre_matchs_gagnes
self.nombre_matchs_nuls = nombre_matchs_nuls
self.nombre_matchs_perdus = nombre_matchs_perdus
}
}
class Club: Codable {
let name: String
let url: logo
init(name: String, url: logo) {
self.name = name
self.url = url
}
}
class logo: Codable {
let url: String
init(url: String) {
self.url = url
}
}
答案 0 :(得分:2)
您可以为此使用自定义的CodingKeys。结帐Encoding and Decoding Custom Types
示例:
struct Foo: Codable {
var bar: String
var baz: Int
enum CodingKeys: String, CodingKey {
case bar = "1"
case baz = "2"
}
}
let json = "{\"1\":\"bar\",\"2\":\"baz\"}".data(using: .utf8)
let decoder = JSONDecoder()
let foo = try decoder.decode(Foo.self, from: json)
// foo.bar = 'bar'
// foo.baz = 'baz'
// this also works with encoding
let foo = Foo(bar: "MyBar", baz: "MyBaz")
// foo encodes to {"1":"MyBar", "2":"MyBaz"}
嵌套示例 struct FooBar:可编码{ var foo:Foo var bar:字符串 var baz:Int }
struct Foo: Codable {
var bar1: String
var bar2: String
var bar3: String
var bar4: String
var bar5: String
var bar6: String
enum CodingKeys: String, CodingKey {
case bar1 = "1"
case bar2 = "2"
case bar3 = "3"
case bar4 = "4"
case bar5 = "5"
case bar6 = "6"
}
}
这与json结构相同:
{
"foo": {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six"
},
"bar": "Barrr",
"baz": "Bazz"
}
答案 1 :(得分:1)
您可以使用CodingKeys
示例:
struct MyModel: Codable {
let first: String
enum CodingKeys: String, CodingKey {
case first = "1"
}
}