【发布时间】:2021-01-12 12:38:29
【问题描述】:
我有这个JSON 数据:
{
"cities": [
{
"id": 1,
"name": "Paris",
"country_code": "FR",
"attractions": [
"CityHall",
"Theatre",
"Port"
],
"population": 0
},
{
"id": 2,
"name": "Nice",
"country_code": "FR",
"attractions": [
"CityHall"
],
"population": 0
},
{
"id": 3,
"name": "Berlin",
"country_code": "DE",
"attractions": [
"Theatre",
"Port"
],
"population": 0
},
{
"id": 4,
"name": "Munich",
"country_code": "DE",
"attractions": [
"Theatre"
],
"population": 0
},
{
"id": 5,
"name": "Amsterdam",
"country_code": "NL",
"attractions": [
"Theatre",
"Port"
],
"population": 0
},
{
"id": 6,
"name": "Leiden",
"country_code": "NL",
"attractions": [
"CItyHall",
"Theatre"
],
"population": 0
}
]
}
我正在使用 Moya .request(.getCities).map([City].self, atKeyPath: "cities") 使用对象对其进行解码:
struct City {
let id: Int
let name: String
let countryCode: String
//let attractions: [Attraction]
let population: Int
}
extension City: Decodable {
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case countryCode = "countryCode"
//case attractions = "attractions"
case population = "population"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
countryCode = try container.decode(String.self, forKey: .countryCode)
//attractions = try container.decode([Attraction].self, forKey: .attractions)
population = try container.decode(Int.self, forKey: .population)
}
}
简单而漂亮,但问题是我不知道如何将attractions 数组放入此处。我将它作为enum 并尝试使用codingPath 获取密钥
enum Attraction: String {
case CityHall
case Theatre
case Port
}
extension Attraction: Decodable {
enum CodingKeys: String, CodingKey {
// confusion mode initiated :) do I use it the same as in struct here?
case cityHall = "CityHall"
case theatre = "Theatre"
case port = "Port"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let attraction = container.codingPath.first!.stringValue // that would get the first key into string but how to deal with enum?
}
}
另外,如果这样可以很好地解码attractions,那么City 对象可以解码嵌套对象/数组吗?
【问题讨论】:
-
atractions在您的 JSON 中拼写错误。你能做点什么吗?