-1

I have the below json and I want to create model for the json with codable.

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

Model

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

I don't need the key data. I want to set the value of data to empDetails property

How can I do this with init(from decoder: Decoder) throws method?

iOSDev
  • 326
  • 2
  • 10
  • 3
    Have a look at [quicktype.io](https://app.quicktype.io/?l=swift). – vadian Aug 13 '19 at 12:24
  • @vadian I think you didn't understand my question. I have `empDetails->data` in json. I don't want that data in my struct. – iOSDev Aug 13 '19 at 12:28
  • @vadian In my json type of `empDetails` is `[String:Any]` and type of `data` is `[[String:Any]]`. I can create a nested struct with `Root->EmpDetails->Data->[Emp]`. Here I want to avoid the `data` in my struct – iOSDev Aug 13 '19 at 12:30
  • @vadian Ok. I will check it – iOSDev Aug 13 '19 at 12:31

1 Answers1

0

Simply create enum CodingKeys and implement init(from:) in struct Root to get that working.

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)
    }
}
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • Thanks for your answer. But check my josn. It has `empDetails` key and `data` key inside that. I guess your answer wont work – iOSDev Aug 13 '19 at 12:23
  • @iOSDev Sorry for the misunderstanding. I've updated the answer as per the requirement,. – PGDev Aug 13 '19 at 12:28
  • It works. If we use custom `init` method can't we just use the one property `empDetails` inside the `init` method. I get _Return from initializer without initializing all stored properties_ error if I comment `id = ...` and `name = ...` from the `init` method – iOSDev Aug 13 '19 at 13:02