[英]Swift Decode JSON - can not decode
我無法解碼我的 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]
}
我不認為您想以這種方式構建代碼。 您有一個層次結構,您正試圖在更扁平的結構中捕獲該層次結構。
Response
CommentsList
Comments
Title
Comment
Comment
...
Comments
...
所以,你可能想做這樣的事情:
struct Response: Decodable {
var commentsArray: [Comments]
init(from decoder: Decoder) {
let container = try! decoder.container(keyedBy: ResponseCodingKeys.self)
let response = try! container.nestedContainer(keyedBy: ListCodingKeys.self, forKey: .response)
commentsArray = try! response.decode([Comments].self, forKey: .commentsArray)
}
enum ResponseCodingKeys: String, CodingKey { case response = "Response" }
enum ListCodingKeys: String, CodingKey { case commentsArray }
}
struct Comments: Decodable {
var id = UUID()
var title: String
var comments: [String]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.