首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift解码JSON -无法解码

Swift解码JSON -无法解码
EN

Stack Overflow用户
提问于 2020-02-12 01:56:57
回答 2查看 250关注 0票数 0

我无法解码我的JSON文件。如果我只解码一个字符串,它就能工作,但现在我的struct就不能工作了。我有什么地方做错了吗?

我想要解码的结构:

代码语言:javascript
复制
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:

代码语言:javascript
复制
{"Response": {
    "commentsArray":[
      {
        "title": "someTitle",
        "comments": [
          "optionOne",
          "optionTwo"
        ]
      },
      {
        "title": "title",
        "comments": [
          "optionOne",
          "optionTwo"
        ]
      },
      {
        "title": "someto",
        "comments": [
          "optionOne",
          "optionTwo"
        ]
      }
    ]
    }
  }
EN

回答 2

Stack Overflow用户

发布于 2020-02-12 02:05:21

使用这些结构来解码您的json

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2020-02-12 02:59:59

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

代码语言:javascript
复制
Response
    CommentsList
        Comments
            Title
            Comment
            Comment
            ...
        Comments
        ...

因此,您可能想要这样做:

代码语言:javascript
复制
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]
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60174837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档