如何使用可编码的JSON创建模型

时间:2019-08-13 12:16:03

标签: swift codable

我有下面的json,我想用可编码的json模型。

{
    id = 1;
    name = "abc";
    empDetails = {
    data = [{
        address = "xyz";
        ratings = 2;
        "empId" = 6;
        "empName" = "def";
    }];
    };
}

型号

struct Root: Codable {
    let id: Int
    let name: String
    let empDetails:[Emp]
    struct Emp: Codable {
        let address: String
        let ratings: Int
        let empId: Int
        let empName: String
    }
}

我不需要密钥data。我想将data的值设置为empDetails属性

如何使用init(from decoder: Decoder) throws方法执行此操作?

1 个答案:

答案 0 :(得分:0)

只需创建 enum CodingKeys 并在init(from:)中实现 struct Root 即可使工作正常。

struct Root: Decodable {
    let id: Int
    let name: String
    let empDetails: [Emp]

    enum CodingKeys: String, CodingKey {
        case id, name, empDetails, data
    }

    struct Emp: Codable {
        let address: String
        let ratings: Int
        let empId: Int
        let empName: String
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        name = try container.decode(String.self, forKey: .name)
        let details = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .empDetails)
        empDetails = try details.decode([Emp].self, forKey: .data)
    }
}