每次尝试在我的程序中解析 JSON 时,我都会遇到以下错误。我似乎无法弄清楚。
“预期解码 String 但发现了一个数组。”, underlyingError: nil
这是我一直在纠结的代码:
struct Book: Decodable {
let id: Int
let title: String
let chapters: Int
var pages: [Page]?
}
struct Page: Decodable {
let id: Int
let text: [String]
}
struct Chapter: Decodable {
var chapterNumber: Int
}
func fetchJSON() {
let urlString = "https://api.myjson.com/bins/kzqh3"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, _, err) in
if let err = err {
print("Failed to fetch data from", err)
return
}
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let books = try decoder.decode([Book].self, from: data)
books.forEach({print($0.title)})
} catch let jsonErr {
print("Failed to parse json:", jsonErr)
}
}.resume()
}
最佳答案
您确定这是真正的错误消息吗?
其实错误应该是
"Expected to decode String but found a dictionary instead."
key text
的值不是字符串数组,而是字典数组
struct Page: Decodable {
let id: Int
let text: [[String:String]]
}
不需要结构 Chapter
。
或者编写一个自定义初始化程序,并将包含章节编号作为键和文本作为值的字典解码到 Chapter
的数组中
struct Book: Decodable {
let id: Int
let title: String
let chapters: Int
let pages: [Page]
}
struct Page: Decodable {
let id: Int
var chapters = [Chapter]()
private enum CodingKeys : String, CodingKey { case id, chapters = "text" }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
var arrayContainer = try container.nestedUnkeyedContainer(forKey: .chapters)
while !arrayContainer.isAtEnd {
let chapterDict = try arrayContainer.decode([String:String].self)
for (key, value) in chapterDict {
chapters.append(Chapter(number: Int(key)!, text: value))
}
}
}
}
struct Chapter: Decodable {
let number : Int
let text : String
}
关于json - 使用 Swift 4 Decodable 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49638632/