ios - Swift Decode JSON - 无法解码
问题描述
我无法解码我的 JSON 文件。如果我只解码一个字符串,但现在使用我的结构它不起作用。有什么我做错了吗?
我要解码的结构:
struct Comment: Decodable, Identifiable {
var id = UUID()
var title : String
var comments : [String]
private enum Keys: String, CodingKey {
case response = "Response"
case commentsArray = "commentsArray"
case title = "title"
case comments = "comments"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: Keys.self)
let response = try values.nestedContainer(keyedBy: Keys.self, forKey: .response)
let commentsArray = try response.nestedContainer(keyedBy: Keys.self, forKey: .commentsArray)
title = try commentsArray.decodeIfPresent(String.self, forKey: .title)!
comments = try commentsArray.decodeIfPresent([String].self, forKey: .comments)!
}
}
我的 JSON:
{"Response": {
"commentsArray":[
{
"title": "someTitle",
"comments": [
"optionOne",
"optionTwo"
]
},
{
"title": "title",
"comments": [
"optionOne",
"optionTwo"
]
},
{
"title": "someto",
"comments": [
"optionOne",
"optionTwo"
]
}
]
}
}
解决方案
使用这些结构来解码你的 json
struct Response: Codable {
var response : Comments
private enum Keys: String, CodingKey {
case response = "Response"
}
}
struct Comments: Codable {
var commentsArray : [comment]
}
struct comment: Codable {
let title: String
let comments: [String]
}
推荐阅读
- node.js - 在nodejs外部获取回调值
- cookies - 无法在 clojure 环中设置 cookie
- arrays - 尝试将 grep 结果存储到数组中,但希望将每个值存储为不同的键
- c# - c#强名称程序集反射加载接口强制转换问题
- python - 在 WSL Ubuntu 中绘制图形的反复出现的问题
- python - 从字符串列表创建字典,其中每个字符串包含一个代码和索引
- file - 如何在命令行 Racket 的 REPL 中加载和使用 .rkt 文件?
- c# - 如何注册强类型 SignalR Core 集线器?
- python - 在中断和尝试更改循环值之后,这可能是其他条件吗?
- sql - 向主从表 Delphi 添加新值时绑定外键