json - Swift Json KeyNotFound
问题描述
请帮助完成这项工作我一直在尝试找出 JSON 和 Swift 一个星期,并且今天到目前为止面对这个问题 5 个小时。
收到错误
解码 JSON 时出错 keyNotFound(CodingKeys(stringValue: "MP", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "MP", intValue: nil) (“MP”)。”,基础错误:无))
年为零
代码
struct UserDay: Codable {
let MP: UserMP
let WP: UserWP
}
struct UserMP: Codable {
let M: [UserM]
let S: [UserS]
}
struct UserM : Codable {
let title: String
let description: String
let time: String
}
struct UserS : Codable {
let title: String
let description: String
let time: String
}
struct UserWP: Codable {
let WP: [WPData]
}
struct WPData: Codable {
let title: String
let values: [Int]
}
class LogDataHandler {
public func grabJSONInfo(){
guard let jsonURL = Bundle(for: type(of: self)).path(forResource: "newLogData", ofType: "json") else { return }
guard let jsonString = try? String(contentsOf: URL(fileURLWithPath: jsonURL), encoding: String.Encoding.utf8) else { return }
// print(jsonString)
// Print Info for TESTING
var year: UserDay?
do {
year = try JSONDecoder().decode(UserDay.self, from: Data(jsonString.utf8))
} catch {
print("ERROR WHEN DECODING JSON \(error)")
}
guard let results = year else {
print("YEAR IS NIL")
return
}
print(results)
}
}
JSON
{
"01/01/2020": {
"MP" : {
"M" : [
{"title" : "m1", "description" : "1", "time" : "12:30pm"},
{"title" : "m2", "description" : "2", "time" : "1:30pm"},
{"title" : "m3", "description" : "3", "time" : "2:30pm"}
],
"S" : [
{"title" : "s1", "description" : "1", "time" : "1pm"}
]
},
"WP" : [
{ "title" : "abc", "values" : [12, 10, 6]},
{ "title" : "def", "values" : [8]}
]
},
"01/29/2020": {
"MP" : {
"M" : [{"title" : "m1", "description" : "1", "time" : "12:30pm"}],
"S" : [{"title" : "s1", "description" : "1", "time" : "12:30pm"}]
},
"WP" :[{ "title" : "def", "values" : [8]}]
}
}
解决方案
首先,let WP: UserWP
用数组替换:
struct UserDay: Codable {
let MP: UserMP
let WP: [WPData]
}
然后解码[String:UserDay]
而不是UserDay
:
try JSONDecoder().decode([String:UserDay].self, from: Data(jsonString.utf8))
请注意,这将返回一个带有键值对的字典"01/01/2020"
: UserDay object
。
这意味着您不能将字典分配给[String: UserDay]
变量UserDay
。相反,您可以通过某个日期的键(例如“01/01/2020”)访问字典,然后将其分配给您的UserDay
变量:
let result = try JSONDecoder().decode([String:UserDay].self, from: Data(jsonString.utf8))
let someYear = result["01/01/2020"]
请注意, someYear 将是可选的,因此您可能需要提供默认值或强制解包它。
推荐阅读
- python-3.x - 如何使用多索引数据框绘制两级 x-ticklabels
- java - 使用java将文件从父目录移动到子目录
- testing - Testcafe:轮询测试
- mysql - 同一列表/表中的 Linq 子查询
- python - Mac OS 上 PyQT5 应用程序中 textedit.clear() 的奇怪行为
- shell - 特定列号与特定字符串的模式匹配。没有分隔符或分隔符
- c# - AWS Lambda Selenium WebDriver - 加载 ibglib-2.0.so 时出错
- angular - 预期 = 1,接收 = 0 - 为什么我的函数没有在 Angular 测试中调用?
- gitlab - 有什么方法可以禁用 GitLab 默认指标?
- reactjs - 在 Elastic Beanstalk 上使用 Docker 部署 ReactJS - 随机超时和/或失败