用于解析JSON的SWIFT模型

时间:2018-06-29 17:52:06

标签: json swift codable

我需要解析JSON的数据。为此,我将使用协议 Codable 。 收到的json看起来像这样(这是我感兴趣的部分):

(
    {
        description = mySecondGist;
        files =         {
            "gistfile1.txt" =             {
                filename = "gistfile1.txt";
                language = Text;
                "raw_url" = "https://gist.githubusercontent.com/VladimirKhuraskin/9ca2362c09cebcc16bd74f51f267231a/raw/74caacd3ad3eedb369a07b926327d2ef37e3eefc/gistfile1.txt";
                size = 17;
                type = "text/plain";
            };
        };
    }
)

我制作了这个模型:

struct Gists: Codable {
    var description: String?
    var files: DetailGist?

    private enum CodingKeys: String, CodingKey {
        case description
        case files
    }
}

struct DetailGist: Codable {
    var filename: String?
    var rawUrl: String?

    private enum FileCodingKeys: String, CodingKey {
        case filename
        case rawUrl = "raw_url"
    }
}

这是正确的模型吗?还是需要完成?我对

感到困惑
files =         {
            "gistfile1.txt" = 

谢谢!

1 个答案:

答案 0 :(得分:1)

不,文件是字典。这就是JSON中的{}标记的含义。您希望自己的Gists模型成为

var files: [String: DetailGist]?