【问题标题】:This code parses a json-format URL to create a typical news feed此代码解析 json 格式的 URL 以创建典型的新闻提要
【发布时间】:2020-04-01 00:17:28
【问题描述】:

我从codingwithchris.com Xcode 教程中得到这个,非常好。我试图用我的 xml 格式 URL 的 URL 代替 Chris 的 json 格式 newsapi.org URL。 正如预期的那样,我得到“解析 json 时出错”。感谢任何快速提示。

let stringUrl = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8c4d5faa662f4dce849d17d89e86ca14"
let url = URL(string: stringUrl)
guard url != nil else {
    print("Couldn't create url object")
    return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { (data, response, error) in
  if error == nil && data != nil {
      let decoder = JSONDecoder()
      do {
          let articleService = try decoder.decode(ArticleService.self, from: data!)
          if articleService.articles == nil {
              return
          }
          let articles = articleService.articles!
          DispatchQueue.main.async {
              self.delegate?.articlesRetrieved(articles)
           } // end DispatchQueue.main.sync
       } end do
       catch {
           print("Error parsing the json")
       } // End catch

  } // End if

} // End dataTask

dataTask.resume()

【问题讨论】:

  • 能否添加 ArticleService 的代码?我尝试使用一个简单的结构,它奏效了。
  • 除了添加 ArticleService 的代码之外,您还可以从 catch 块中获取错误变量并打印它以获得更多信息:`catch let e { print("解析 json 时出错:(e)" ) } // 结束捕获 `
  • 你还没有说出你想要达到的目标。
  • 如果你答对了,请将答案设置为正确答案。

标签: json swift xml xcode


【解决方案1】:

很可能您在解码 json 时使用了不正确的结构。这就是你需要的。

struct Response: Codable {
    let status: String
    let totalResults: Int
    let articles: [Article]
}

struct Article: Codable {
    let source: Source
    let author: String?
    let title, description, url, urlToImage: String
    let publishedAt: String
    let content: String?
}

struct Source: Codable {
    let id: String?
    let name: String
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多