【发布时间】:2020-02-11 17:56:56
【问题描述】:
我无法解码我的 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"
]
}
]
}
}
【问题讨论】:
-
你遇到了什么错误?