Swift 4 JSON Decodable with multidimensional and multitype array

后端 未结 5 1474
天命终不由人
天命终不由人 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:09

    Solution

    public struct UncertainValue: Decodable {
        public var tValue: T?
        public var uValue: U?
    
        public var value: Any? {
            return tValue ?? uValue
        }
    
        public init(from decoder: Decoder) throws {
            let container = try decoder.singleValueContainer()
            tValue = try? container.decode(T.self)
            uValue = try? container.decode(U.self)
            if tValue == nil && uValue == nil {
                //Type mismatch
                throw DecodingError.typeMismatch(type(of: self), DecodingError.Context(codingPath: [], debugDescription: "The value is not of type \(T.self) and not even \(U.self)"))
            }
    
        }
    }
    

    Example

    {
    "results": [{
            "name": "Gala",
            "age": 1,
            "type": "Pug"
        }, {
            "name": "Keira",
            "age": "7",
            "type": "Collie Rough"
        }]
    }
    

    Usage

    struct Dog: Decodable, CustomStringConvertible {
        var name: String
        var age: UncertainValue
        var type: String
    
        var description: String {
            return "\(name) is a lovely \(type) of \(age.value!) years old"
        }
    }
    

提交回复
热议问题