Swift 4 JSON Decodable with multidimensional and multitype array

后端 未结 5 1460
天命终不由人
天命终不由人 2020-11-30 13:32
{
\"values\":[
[1,1,7,\"Azuan Child\",\"Anak Azuan\",\"12345\",\"ACTIVE\",\"Morning\",7,12,\"2017-11-09 19:45:00\"],
[28,1,0,\"Azuan Child2\",\"Amran\",\"123456\",\"         


        
5条回答
  •  春和景丽
    2020-11-30 14:00

    As you said, your json array is multi-type but you are trying to decode all into String. Default conformance of String to Decodable does not allow that. The only solution comes into my mind is to introduce new type.

    struct IntegerOrString: Decodable {
        var value: Any
    
        init(from decoder: Decoder) throws {
            if let int = try? Int(from: decoder) {
                value = int
                return
            }
    
            value = try String(from: decoder)
        }
    }
    
    struct ChildrenTable: Decodable {
        var values: [[IntegerOrString]]?
    }
    

    Run online

提交回复
热议问题