序列化JSON“ keyNotFound”

时间:2018-10-10 14:17:36

标签: 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错误?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

问题在于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()
}