"Expected to decode String but found a number instead." 解码 JSON 时出现问题



我正在尝试从https://en.wikipedia.org/w/api.php?format=json&action=查询&prop=提取|页面图像&exintro=&explaintext=&indexpageids&重定向=1&髓核大小=500&title=坎特伯雷%20bells

{"batchcomplete":"","query":{"normalized":[{"from":"canterbury bells","to":"Canterbury bells"}],"redirects":[{"from":"Canterbury bells","to":"Campanula medium"}],"pageids":["5372595"],"pages":{"5372595":{"pageid":5372595,"ns":0,"title":"Campanula medium","extract":"Campanula medium, common name Canterbury bells, is an annual or biennial flowering plant of the genus Campanula, belonging to the family Campanulaceae. In floriography, it represents gratitude, or faith and constancy.","thumbnail":{"source":"https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Campanulaceae_-_Campanula_medium-4.JPG/500px-Campanulaceae_-_Campanula_medium-4.JPG","width":500,"height":375},"pageimage":"Campanulaceae_-_Campanula_medium-4.JPG"}}}} 

我正在使用以下代码,我正在尝试获取缩略图的源URL,以及其他内容。

我的数据模型:

struct FlowerData: Decodable {
let query: Query
}
struct Query: Decodable {
let pageids: [String]
let pages: [String: Pages]
let normalized: [[String: String]]
}
struct Pages: Decodable {
let extract: String
let thumbnail: [String: String]
}

我的解析代码:

func parseJSON(_ flowerData: Data) -> FlowerModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(FlowerData.self, from: flowerData)
let pageID = decodedData.query.pageids[0]
let name = decodedData.query.normalized[0]["from"]
let description = decodedData.query.pages[pageID]?.extract
let thumbnail = decodedData.query.pages[pageID]?.thumbnail["source"]
let flower = FlowerModel(flowerName: name!, description: description!, thumbnail: thumbnail!)
return flower
} catch {
delegate?.didFailWithError(error: error)
return nil
}
}

然而,当我运行此代码时,我会遇到以下错误:

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "query", intValue: nil), CodingKeys(stringValue: "pages", intValue: nil), _JSONKey(stringValue: "5372595", intValue: nil), CodingKeys(stringValue: "thumbnail", intValue: nil), _JSONKey(stringValue: "width", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))

唯一失败的是获取缩略图的URL。名称和描述按计划运行。我做错了什么?任何帮助都将不胜感激。

错误非常明显。你需要解码一个结构,但你将缩略图定义为字典:

所以你只需要改变

struct Pages: Decodable {
let extract: String
let thumbnail: [String: String]
}

struct Pages: Decodable {
let extract: String
let thumbnail: Thumbnail
}

并将缩略图结构定义为:

struct Thumbnail: Decodable {
let source: String
let width, height: Int
}

然后在您的方法中,您还需要更改

let thumbnail = decodedData.query.pages[pageID]?.thumbnail["source"]

let thumbnail = decodedData.query.pages[pageID]?.thumbnail.source

最新更新