json - 序列化 JSON "keyNotFound"时出错

标签 json swift codable

我正在练习在 Swift 4 中解析 JSON 的新方法,并且我正在使用纽约时报 API - 我发现很难阅读 JSON 的结构,因为 API 页面只是 shows a wall of text

我已经为要提取的数据(标题、摘要)编写了一个小结构:

struct Stories: Decodable {
    let title: String
    let abstract: String
}

这是我为获取 JSON 而调用的函数:

func getJSON() {
    let jsonUrlString = "https://api.nytimes.com/svc/topstories/v1/business.json?api-key=f4bf2ee721031a344b84b0449cfdb589:1:73741808"
    guard let url = URL(string: jsonUrlString) else {return}

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else {return}

        do {

            let stories = try
                JSONDecoder().decode(Stories.self, from: data)
            print(stories.title, stories.abstract)

        } catch let jsonErr {
            print("Error serializing JSON", jsonErr)
        }
    }.resume()
}

当我运行该应用程序时,我在控制台中看到错误消息:

Error serializing JSON keyNotFound(CodingKeys(stringValue: "title", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))

所以看起来它没有找到“title”的值。我可以在这里做些什么不同的事情,我是否错误地设置了 Struct?还是我使用的 JSONDecorder 有误?

感谢您的帮助!

最佳答案

问题是 Stories 嵌套在外部 Dictionary 中,您还需要对其进行解析。

struct TopStoriesResponse: Codable {
    let status:String
    let results:[Story]
}

struct Story: Codable {
    let title: String
    let abstract: String
}

func getTopStories() {
    let jsonUrlString = "https://api.nytimes.com/svc/topstories/v1/business.json?api-key=f4bf2ee721031a344b84b0449cfdb589:1:73741808"
    guard let url = URL(string: jsonUrlString) else {return}

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data, err == nil else {
            print(err!)
            return
        }

        do {
            let response = try JSONDecoder().decode(TopStoriesResponse.self, from: data)
            print(response.results.first?.title, response.results.first?.abstract)

        } catch let jsonErr {
            print("Error serializing JSON", jsonErr)
        }
    }.resume()
}

关于json - 序列化 JSON "keyNotFound"时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742333/

相关文章:

java - GSON 解析器在循环 json 时跳过对象

javascript - 切片多维 JSON 数组中一列的最后 2 个对象

xcode - 快速 UITableView 设置 rowHeight

json - 如何比较两个 JSON 请求?

android - GSON getAsString() 方法不会从 JSON 元素中去除双引号?

ios - 使用 AVAssetDownloadTask 进行 HLS 缓存

Swift TDD 和异步 URLSession - 如何测试?

swift - 泛型类型 'T' 不符合协议(protocol) 'Encodable'

Swift Codable 在嵌套字典上崩溃

json - Swift 4 解码复杂的嵌套 JSON