GitHub API not parsing



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

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

描述似乎是 GitHub API 中的一个可选字段,当存储库未定义描述时,它会作为null返回。这意味着您需要将描述字段设置为String?,并切换到使用decodeIfPresent以说明它是可选的。

关于该特定 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)
}
}

相关内容

  • 没有找到相关文章

最新更新