Roi*_*lia 1 containers json swift4 codable decodable
我试图了解如何将这个多容器 JSON 解析为一个对象。我已经尝试过这种方法(Mark answer),但他解释了如何使用一级容器解决它。出于某种原因,我无法模仿多个容器的行为。
 {
     "graphql": {
        "shortcode_media": {
          "id": "1657677004214306744",
          "shortcode": "BcBQHPchwe4"
        }
     }
  }
class Post: Decodable {
    enum CodingKeys: String, CodingKey {
        case graphql // The top level "user" key
        case shortcode_media
    }
    enum PostKeys: String, CodingKey {
        case id
    }
    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let post = try values.nestedContainer(keyedBy: PostKeys.self, forKey: .shortcode_media)
        self.id = try post.decode(String.self, forKey: .id)
    }
    var id: String
}
我越来越:
Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get KeyedDecodingContainer<PostKeys> -- no value found for key \"shortcode_media\"", underlyingError: nil))
任何帮助将不胜感激,谢谢!
正如 vadian 指出的那样,您没有匹配 JSON 结构。没有shortcode_media像您在CodingKeys.
为了使用自定义解码器对其进行解码,您需要遍历每个级别并进行处理。
class Post: Decodable {
    enum CodingKeys: String, CodingKey {
        case graphql
    }
    enum GraphQLKeys: String, CodingKey {
        case shortcode_media
    }
    enum PostKeys: String, CodingKey {
        case id
    }
    required init(from decoder: Decoder) throws {
        // unload the top level
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // Unload the graphql key
        let graphql = try container.nestedContainer(keyedBy: GraphQLKeys.self, forKey: .graphql)
        // unload the shortcode_media key
        let post = try graphql.nestedContainer(keyedBy: PostKeys.self, forKey: .shortcode_media)
        // Finally, unload the actual object
        self.id = try post.decode(String.self, forKey: .id)
    }
    var id: String
}
| 归档时间: | 
 | 
| 查看次数: | 2175 次 | 
| 最近记录: |