繁体   English   中英

Swift 解码 JSON - 无法解码

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM