如何使用 codable 为此 json 创建模型

How to create model for this json with codable

我有以下 json,我想为 json 和 codable 创建模型。

{
    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 方法执行此操作?

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

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)
    }
}