ios - 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)
我很难理解描述字段有什么特别之处。任何形式的帮助将不胜感激。谢谢。
解决方案
描述似乎是 GitHub API 中的一个可选字段,当存储库未定义描述时,它会以null
. 这意味着您需要将描述字段设置为 aString?
并切换到 usingdecodeIfPresent
以说明它是可选的这一事实。
推荐阅读
- http - 如何将 http 服务调用返回的值绑定到 Angular6 中 UI 中的字段下拉列表
- vb.net - 如何减少pdf中嵌入的重复字体
- c - 在 C 中测量没有 pthread 的开销
- css - 如何在 ODOO 中更改 One2many 背景的颜色?
- angular - 如何获取一个元素的类列表到另一个元素
- javascript - FB.ui 回调从 2018 年 2 月 1 日起不起作用
- javascript - 可以基于 jsonpath 更新 json 的 JavaScript 库或模块是什么?
- javascript - 输入到 td 的选择器 jquery
- azure - 通过 ARM 模板将现有 VM 添加到 Azure 负载均衡器
- java - CompletableFuture.runAsync(() ->... 带有非最终变量