首页 > 解决方案 > GitHub API 未解析

问题描述

这是我从 Github 获得的响应请求的 JSON 的一部分

{
  "total_count": 1657,
  "incomplete_results": false,
  "items": [
    {
      "id": 68911683,
      "node_id": "MDEwOlJlcG9zaXRvcnk2ODkxMTY4Mw==",
      "name": "tetros",
      "full_name": "daniel-e/tetros",
      "private": false,
      "html_url": "https://github.com/daniel-e/tetros",
      "description": "Tetris that fits into the boot sector.",
      "size": 171,
      "stargazers_count": 677,
      "watchers_count": 677,
      "language": "Assembly",
    }
    ]
}

这是我的模特

struct RepoGroup:Codable {

    var items:[Repo]

}

struct Repo: Codable {

var fullName:String
var stars:Int
var watchers:Int

init(url:String,star:Int,watcher:Int) {
    fullName = url
    stars = star
    watchers = watcher
}

enum MyStructKeys: String, CodingKey {
    case fullName = "full_name"
    case stars = "stargazers_count"
    case watchers = "watchers_count"
}

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: MyStructKeys.self)
    let fullName: String = try container.decode(String.self, forKey: .fullName)
    let stars: Int = try container.decode(Int.self, forKey: .stars)
    let watchers: Int = try container.decode(Int.self, forKey: .watchers)

    self.init(url: fullName, star: stars, watcher: watchers)
}

}

到目前为止,一切都很好。但是,一旦我description:String在模型中添加字段,JSON 解码器就莫名其妙地无法解析。

这是我的解析器

let model = try JSONDecoder().decode(RepoGroup.self, from: dataResponse)

我很难理解描述字段有什么特别之处。任何形式的帮助将不胜感激。谢谢。

标签: iosjsonparsinggithub-apicodable

解决方案


描述似乎是 GitHub API 中的一个可选字段,当存储库未定义描述时,它会以null. 这意味着您需要将描述字段设置为 aString?并切换到 usingdecodeIfPresent以说明它是可选的这一事实。


推荐阅读