I can not decode my JSON File. It works if I decode only a single string but now with my struct it does not work. Is there anything that I do wrong?
My struct that i want to decode:
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)!
}
}
My JSON:
{"Response": {
"commentsArray":[
{
"title": "someTitle",
"comments": [
"optionOne",
"optionTwo"
]
},
{
"title": "title",
"comments": [
"optionOne",
"optionTwo"
]
},
{
"title": "someto",
"comments": [
"optionOne",
"optionTwo"
]
}
]
}
}