Home > Software design >  decoding a [String: Int] dictionary from JSON
decoding a [String: Int] dictionary from JSON

Time:07-31

Using the quicktype.io I reflected the following JSON...

{
"message": "The data were fetched successfully.",
"data": {
    "date": "2022-07-22",
    "day": 149,
    "resource": "https://www.someWebsite.com",
    "stats": {
        "personnel_units": 39000,
        "tanks": 1704,
        "armoured_fighting_vehicles": 3920,
        "artillery_systems": 863,
        "mlrs": 251,
        "aa_warfare_systems": 113,
        "planes": 221,
        "helicopters": 188,
        "vehicles_fuel_tanks": 2803,
        "warships_cutters": 15,
        "cruise_missiles": 167,
        "uav_systems": 713,
        "special_military_equip": 72,
        "atgm_srbm_systems": 4
    },
    "increase": {
        "personnel_units": 150,
        "tanks": 0,
        "armoured_fighting_vehicles": 8,
        "artillery_systems": 4,
        "mlrs": 0,
        "aa_warfare_systems": 0,
        "planes": 0,
        "helicopters": 0,
        "vehicles_fuel_tanks": 22,
        "warships_cutters": 0,
        "cruise_missiles": 0,
        "uav_systems": 3,
        "special_military_equip": 0,
        "atgm_srbm_systems": 0
    }
}
}

into the classic Swift struct ...

    struct DataModel: Codable {
    var message: String
    var data: ObjectsModel
}

struct ObjectsModel: Codable {
    var date: String
    var day: Int
    var resource: String
    var stats, increase: [String: Int]
}

My issue is about stats and increase properties. I simply cannot find a way to either set the CodingKeys for the keys that come in those properties or set the decoding strategy to convert them to CamelCase.

Calling decoder.keyDecodingStrategy = .convertFromSnakeCase doesn't seem to work and the keys are still displayed in SnakeCase...

CodePudding user response:

As much as I understand, you need a new struct for both stats and increase, or it would be a better approach.

          struct DictionaryItem: Codable {
             let personnelUnits: Int 
             let tanks: Int
             let armouredFightingVehicles: Int

             enum CodingKeys: String, CodingKey { 
                 case personnelUnits = "personnel_units"
                 case tanks
                 ...
           }

That way you can use it defining increases and stats as DictionaryItem

  • Related