我无法解码我的JSON文件。如果我只解码一个字符串,它就能工作,但现在我的struct就不能工作了。我有什么地方做错了吗?
我想要解码的结构:
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"
]
}
]
}
}发布于 2020-02-12 02:05:21
使用这些结构来解码您的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]
}发布于 2020-02-12 02:59:59
我不认为你想以这种方式构建你的代码。你有一个层级结构,你正试图在一个更扁平的结构中捕获它。
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]
}https://stackoverflow.com/questions/60174837
复制相似问题