在 Swift 中解码 JSON 时将 Int 转换为 String

Convert Int to String while decoding JSON in Swift

我想将此 JSON 解码为外观正常的结构或 Class 但我面临一个问题,我需要为 属性 年龄创建一个全新的结构, 我怎样才能避免这种情况并将年龄直接保存到 class 人?

还有,把Int转成String就好了

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

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

struct Age: Decodable {
    var age_years: Int
}

我想摆脱 Age 并将其保存为:

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

你可以试试

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