json - 使用 Swift 4 Decodable 解析 JSON

标签 json swift decodable

每次尝试在我的程序中解析 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/

相关文章:

swift - 尝试在另一个数组中使用可解码结构时出现可解码错误

ios - 在ios中将json转换成字典

javascript - 可以用 JSON 发送 javascript 函数吗?

regex - 如何使用正则表达式替换最后一个单词?

Swift 4 使用泛型作为返回值

ios - 在 swift 中无法访问泛型结构的可解码对象中的嵌套值?

javascript - 为什么我从 jsonp 结果中得到相同的引用

jquery 完整日历不显示事件

ios - 在不使用 cocoapods 的情况下向现有项目添加框架

json - 将本地字典复制到全局字典中