Swift - key在Json解码时没有发现错误



Swift中Json的问题-试图解码数据,但得到错误"未找到密钥"。我用另一把钥匙检查过了,它能用,所以也许是名字错了?

我将感激任何提示!

Json:

{
"created": "2021-10-18T14:55:42.537Z",
"count": 2,
"offset": 0,
"places": [
{
"id": "d1ab65f8-d082-492a-bd70-ce375548dabf",
"type": "Studio",
"type-id": "05fa6a09-ff92-3d34-bdbb-5141d3c24f38",
"score": 100,
"name": "Chipping Norton Recording Studios",
"address": "28–30 New Street, Chipping Norton",
"coordinates": {
"latitude": "51.9414",
"longitude": "-1.548"
},
"area": {6 items},
"life-span": {
"begin": "1971",
"end": "1999-10",
"ended": true
}
},
{8 items}
]
}

和我的数据结构:

import Foundation
struct BrainzData: Codable {
let places: [Places]
}
struct Places: Codable {
var coordinates: Coordinates
var lifespan: LifeSpan

enum CodingKeys: String, CodingKey {
case coordinates
case lifespan = "life-span"
}
}
struct Coordinates: Codable {
let longitude: String
let latitude: String
}
struct LifeSpan: Codable {
let begin: String
var ended: Bool
}

尝试解码来自API的所有数据,您可能会看到一些键值对为空。您可能希望将参数更改为最佳值。首先把struct改成

struct Coordinates: Codable {
let longitude: String?
let latitude: String?
}
struct LifeSpan: Codable {
let begin: String?
var ended: Bool?
}

然后记录您的数据,如:

guard let responseData = data else { return }
do {
let jsonData = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers)
let apiResponse = try JSONDecoder().decode(BrainzData.self, from: responseData)
print(apiResponse)

} catch {
print(error)
}

data在会话中是相同的。dataTask func

task = session.dataTask(with: request, completionHandler: { data, response, error in })

相关内容

  • 没有找到相关文章

最新更新