使用swift Combine解码JSON失败



我正在尝试使用Combine读取此JSON数据,但如果我尝试读取release字段,则无法使其工作。地址https://amiiboapi.com/api/返回如下内容:

{
"amiibo": [
{
"amiiboSeries": "Super Smash Bros.", 
"character": "Mario", 
"gameSeries": "Super Mario", 
"head": "00000000", 
"image": "https://raw.githubusercontent.com/N3evin/AmiiboAPI/master/images/icon_00000000-00000002.png", 
"name": "Mario", 
"release": {
"au": "2014-11-29", 
"eu": "2014-11-28", 
"jp": "2014-12-06", 
"na": "2014-11-21"
}, 
"tail": "00000002", 
"type": "Figure"
}, 
{
"amiiboSeries": "Super Mario Bros.", 
"character": "Mario", 
"gameSeries": "Super Mario", 
"head": "00000000", 
"image": "https://raw.githubusercontent.com/N3evin/AmiiboAPI/master/images/icon_00000000-00340102.png", 
"name": "Mario", 
"release": {
"au": "2015-03-21", 
"eu": "2015-03-20", 
"jp": "2015-03-12", 
"na": "2015-03-20"
}, 
"tail": "00340102", 
"type": "Figure"
} 
] 
}

我的模型是这样的:

// MARK: - Amiibo List
struct AmiibosList: Codable {
let amiibo: [Amiibo]
}
// MARK: - Amiibo
struct Amiibo: Codable {
let amiiboSeries: String
let character: String
let gameSeries: String
let head: String
let image: String
let name: String
let release: Release
let tail: String
let type: String
}
// MARK: - Release
struct Release: Codable  {
let au : String?
let eu : String?
let jp : String?
let na : String?
}

我正试图获取这样的数据:

guard let url = URL(string: "https://amiiboapi.com/api/") else {
fatalError("Invalid URL")
}
var publisher = URLSession.shared.dataTaskPublisher(for: url)
.receive(on: RunLoop.main)
.map(.data)
.decode(type: AmiiboList.self, decoder: JSONDecoder())
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Failed with error (err)")
}
}, receiveValue: { value in
print("Received (value)")
//        print(" Received (value.amiibo[0].release)")
})

如果我从我的amiibo结构中注释/删除发布,一切都会正常工作。由于某种原因,我无法检索到发布日期的数据,也不知道为什么。我需要对嵌套的JSON数据做其他操作吗?

通过以下操作,您可以简单地执行:response.amiibo[0].release来获取发布对象。请注意,发布对象包含日期对象,而不是字符串。这应该很有帮助。

func example(data: Data) throws -> Response {
let data = jsonString.data(using: .utf8)!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
return try decoder.decode(Response.self, from: data)
}
struct Response: Codable {
let amiibo: [Amiibo]
}
struct Amiibo: Codable {
let amiiboSeries: String
let character: String
let gameSeries: String
let head: String
let image: URL?
let name: String
let release: Release
let tail: String
let type: String
}
struct Release: Codable {
let au: Date?
let eu: Date?
let jp: Date?
let na: Date?
}

相关内容

  • 没有找到相关文章

最新更新