【问题标题】:Swift Decode JSON - can not decodeSwift Decode JSON - 无法解码
【发布时间】:2020-02-11 17:56:56
【问题描述】:

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

【问题讨论】:

  • 你遇到了什么错误?

标签: ios json swift decode


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我不认为您想以这种方式构建您的代码。你有一个层次结构,你试图在一个更扁平的结构中捕获。

    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]
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多