Swift 从Amadeus快速解码JSON
我在从API解码JSON时遇到问题。 我得到了JSON:Swift 从Amadeus快速解码JSON,swift,decodable,jsondecoder,Swift,Decodable,Jsondecoder,我在从API解码JSON时遇到问题。 我得到了JSON: { "meta": { "count": 1, "links": { "self": "https://test.api.amadeus.com/v1/reference-data/locations?subType=AIRPORT&keyword=barcel&sort=analytics.travelers.score&view=LIGHT&page%5Boffset%5
{
"meta": {
"count": 1,
"links": {
"self": "https://test.api.amadeus.com/v1/reference-data/locations?subType=AIRPORT&keyword=barcel&sort=analytics.travelers.score&view=LIGHT&page%5Boffset%5D=0&page%5Blimit%5D=10"
}
},
"data": [
{
"type": "location",
"subType": "AIRPORT",
"name": "AIRPORT",
"detailedName": "BARCELONA/ES:AIRPORT",
"id": "ABCN",
"self": {
"href": "https://test.api.amadeus.com/v1/reference-data/locations/ABCN",
"methods": [
"GET"
]
},
"iataCode": "BCN",
"address": {
"cityName": "BARCELONA",
"countryName": "SPAIN"
}
}
]
}
我的代码如下所示:
struct Airport: Decodable {
let meta: MetaAirport
let data: AirportInfo
}
struct Address: Decodable{
let countryName: String
let cityName: String
}
struct AirportInfo: Decodable{
let address: Address
let subType: String
let id: String
let type: String
let detailedName: String
let name: String
let iataCode: String
}
struct MetaAirport : Decodable{
let count: Int
let links: Links
}
struct Links : Decodable{
let info: String
private enum CodingKeys : String, CodingKey {
case info = "self"
}
}
我试图在AirportInfo对象上使用JSONDecoder解码json
do {
let airport = try JSONDecoder().decode(Airport.self, from: data!)
print(airport.data.name)
}
catch let err {
print(err)
}
我犯了一个错误
类型不匹配(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“data”,intValue:nil)],debugDescription:“应解码字典,但找到了数组。”,underyingerror:nil))
我做错了什么?在json数据中,地址是一个对象。更改您的代码:
let address: [Address] -> let address: Address
我看到你已经从原文中编辑了你的问题,所以在给定的时间里很难正确地确定问题所在 然而,Codable很好,一种简单的方法是一点一点地构造对象。如果将事物设置为可选,则不需要对象以相同的方式表示JSON。因此,在调试此类问题时,请选择不同的属性,并查看解析的内容。这将允许您一点一点地识别出哪里做错了,而不会导致崩溃并保留正确格式化的部分
另外,专业提示:如果您计划将此代码保留超过1周,请停止使用强制展开
代码>并习惯于正确处理选项。否则,这是一个很难停止的习惯,其他人会讨厌您创建的代码;) 您的模型应该是这样来解析的
struct DataModel: Codable {
let meta: Meta?
let data: [Datum]?
}
struct Datum: Codable {
let type, subType, name, detailedName: String?
let id: String?
let datumSelf: SelfClass?
let iataCode: String?
let address: Address?
enum CodingKeys: String, CodingKey {
case type, subType, name, detailedName, id
case datumSelf = "self"
case iataCode, address
}
}
struct Address: Codable {
let cityName, countryName: String?
}
struct SelfClass: Codable {
let href: String?
let methods: [String]?
}
struct Meta: Codable {
let count: Int?
let links: Links?
}
struct Links: Codable {
let linksSelf: String?
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
}
}
现在,在编辑之后,情况完全不同了。请阅读错误和JSON<代码>数据
显然是一个数组。我编辑代码。我知道我必须在机场结构let data:[AirportInfo]中执行此操作。错误告诉您将data
属性的定义更改为let data:[AirportInfo]
@oyasumi,请查看问题的更新答案。我认为学习如何使用Codable通常比试图在积极开发的结构中发现特定错误更有价值