GitHub API无法解析

时间:2019-08-25 23:36:34

标签: ios json parsing github-api codable

这是我从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)

我正在努力了解描述字段的特殊之处。任何形式的帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

Description在GitHub API中似乎是一个可选字段,当存储库未定义描述时,它将以null的形式返回。这意味着您需要将描述字段设为String?,然后切换到使用decodeIfPresent来说明它是可选的事实。

答案 1 :(得分:0)

关于该特定JSON似乎没有什么不适合描述。还没有测试过,但这就是您的代码的样子?

struct RepoGroup:Codable {

    var items:[Repo]

}

struct Repo: Codable {

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

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

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

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)
    let description: String = try container.decode(String.self, forKey: .description)

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

}