ios - 如何使用 Codable 解析 SubReddits JSON
问题描述
我使用的 URL 是“ https://www.reddit.com/subreddits/.json ”,它将为您提供 Reddit 的 Subreddits 的 JSON 格式。
我的可编码结构模型如下:
struct SubredditsData: Codable {
let data: SubredditData
}
struct SubredditData: Codable {
let children: [Children]
}
struct Children: Codable {
let data: ChildrenData
}
struct ChildrenData: Codable {
let title: String
let icon_img: String
let display_name_prefixed: String
let name: String
}
当然还有 Subreddit 的模型
struct SubredditsModel {
let title: String
let display_name_prefixed: String
let name: String
}
然后我执行了一个请求和实际的解析本身
func parseSubRedditsJSON(_ subredditsRawData: Data) -> [SubredditsModel]? {
let decoder = JSONDecoder()
do {
var subReddits = [SubredditsModel]()
let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)
let data = decodedData.data
let children = data.children
for item in children {
let childrenData = item.data
let title = childrenData.title
let display_name_prefixed = childrenData.display_name_prefixed
let name = childrenData.name
let subReddit = SubredditsModel(title: title, display_name_prefixed: display_name_prefixed, name: name)
subReddits.append(subReddit)
}
return subReddits
} catch {
subredditsDelegate?.didFailWithError(error: error)
return nil
}
}//end of parseSubRedditsJSON
我通过协议委托将数据从请求管理器返回到视图控制器,这工作正常。问题是我在这条线上遇到错误
let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)
错误说:
valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil),
CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 5", intValue: 5),
CodingKeys(stringValue: "data", intValue: nil),
CodingKeys(stringValue: "icon_img", intValue: nil)],
debugDescription: "Expected String value but found null instead.", underlyingError: nil))
我一定遗漏了一些东西,或者没有使用 Swift 可编码实现正确的解析方式。
解决方案
因为有些字段不是可选的,可能需要字符串类型或者null,让它可选就可以解决这个问题。
struct SubredditsData: Codable {
let data: SubredditData
}
struct SubredditData: Codable {
let children: [Children]
}
struct Children: Codable {
let data: ChildrenData
}
struct ChildrenData: Codable {
let title: String?
let icon_img: String?
let display_name_prefixed: String?
let name: String?
}
推荐阅读
- ffmpeg - 在 ffmpeg 命令行中,如何在编码前显示所有过滤器设置及其参数?
- ampl - 有没有办法让 AMPL 做更少的迭代?我希望我的代码在某个点停止运行(在最终优化之前,但有些完成))
- reactjs - 导航时未执行脚本,仅在我刷新页面时才有效
- python - 使用正则表达式宣布函数参数?
- java - Maven 在 jar 或 war 文件名中编译版本
- ruby-on-rails - 找不到stimulus_reflex NPM 包| “npm”通过“npm install -D webpack-cli”安装 CLI
- machine-learning - 梯度下降的波动
- c++ - 从键盘输入并使用 GLUT 增加/减少形状的边
- mitmproxy - 如何在 mitmproxy 上设置节流?
- swift - 如何使 NSTextView 不可选,但允许选择链接