Search code examples
iosjsonswiftjsondecoder

Convert Int to String while decoding JSON in Swift


I want to decode this JSON to a normal-looking Struct or Class but I'm facing a problem that I need to create a whole new Struct for property age, how can I avoid that and save age Directly to class Person?

Also, it would be good to convert Int to String

{
    "name": "John",
    "age": {
                    "age_years": 29
           }
}

struct Person: Decodable {
    var name: String
    var age: Age
}

struct Age: Decodable {
    var age_years: Int
}

I want to get rid of Age and save it like:

struct Person: Decodable {
        var name: String
        var age: String
}

Solution

  • You can try

    struct Person: Decodable {
        let name,age: String
        private enum CodingKeys : String, CodingKey {
              case name, age
        }
        init(from decoder: Decoder) throws {
           let container = try decoder.container(keyedBy: CodingKeys.self)
           name = try container.decode(String.self, forKey: .name)
            do {
                let years = try container.decode([String:Int].self, forKey: .age)
                age = "\(years["age_years"] ?? 0)"
            }
            catch {
                let years = try container.decode([String:String].self, forKey: .age)
                age = years["age_years"] ?? "0"
            }
         
        }
    }