首页 > 解决方案 > Swift Decode JSON - 无法解码

问题描述

我无法解码我的 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"
        ]
      }
    ]
    }
  }

标签: iosjsonswiftdecode

解决方案


使用这些结构来解码你的 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]
}

推荐阅读