带有多维和多类型数组的 Swift 4 JSON 可解码 [英] Swift 4 JSON Decodable with multidimensional and multitype array

查看:30
本文介绍了带有多维和多类型数组的 Swift 4 JSON 可解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
"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","ACTIVE","Evening",1,29,"2017-11-09 19:45:00"]
]
}

好的,这是我从服务器收到的json格式

Ok, this is my json format that i received from the server

现在我想将它解码到我的结构中,但仍然没有运气.

Right now i want to decode it into my struct but still have no luck on it.

struct ChildrenTable: Decodable {
    var values: [[String]]?
}

我在 URLSession 上的调用者方法看起来像这样

And my caller method on URLSession look like this

URLSession.shared.dataTask(with: request) { (data, response, err) in
        guard let data = data else { return }

        let dataAsString = String(data: data, encoding: .utf8)
        print(dataAsString)

        do {
            let children  = try
                JSONDecoder().decode(ChildrenTable.self, from: data)
                print (children)
        } catch let jsonErr {
            print ("Error serializing json: ", jsonErr)
        }
    }.resume()

我得到的错误是

Error serializing json:  
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [Vito_Parent.ChildrenTable.(CodingKeys in _1B826CD7D9609504747BED0EC0B7D3B5).values, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), 
Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0))], 
debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))

我知道数组中有一个 int 值,我只为 var values: [[String]]? (这个错误弹出的原因)转换了 String,但我根本不能使用任何我的结构中的多维数组或元组,因为它遵循可解码的协议.

I know there's an int in the array and i only cast String for the values var values: [[String]]? ( the reason why this error popup), but i simply cannot use any multidimensional array or tuples in my structs since it follow the protocol of Decodable.

我也无法将数据转换为字典,因为它会抛出错误预期解码字典但找到数组"

I also cannot convert the data into dictionary since it will throw error "Expected to decode Dictionary but found array instead"

关于解决这个问题的任何想法?我尝试在数据上转换字符串类型,但仍然没有运气...

Any ideas on solving this problem? i tried casting string type on data but still no luck...

p/s:如果所有的json格式都是字符串类型,就没有问题,但是我没有权限改变它,因为我是从API调用的.

p/s: if all the json format are in string type, there would be no problem, but i dont have the permission on changing that since i call it from API.

推荐答案

正如您所说,您的 json 数组是多类型的,但您正试图将所有内容解码为 String.StringDecodable 的默认一致性不允许这样做.我想到的唯一解决方案是引入新类型.

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]]?
}

在线运行

这篇关于带有多维和多类型数组的 Swift 4 JSON 可解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆