【发布时间】:2018-07-02 19:34:04
【问题描述】:
我试图了解如何将这个多容器 JSON 解析为一个对象。我有tried this approach(马克回答),但他解释了如何使用一级容器来解决它。出于某种原因,我无法模仿多个容器的行为。
{
"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))
任何帮助将不胜感激,谢谢!
【问题讨论】:
标签: json containers swift4 codable decodable