arrays - Swift 4 JSON 可解码多维和多类型数组

标签 arrays json multidimensional-array swift4 decodable

{
"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 格式

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

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

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

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]]? 转换字符串(这个错误弹出的原因),但我根本不能使用任何我的结构中的多维数组或元组,因为它遵循可解码协议(protocol)。

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

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

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

最佳答案

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

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

关于arrays - Swift 4 JSON 可解码多维和多类型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215260/

相关文章:

php - 需要在 PHP 中使用最少的内存使用的类似数组的结构

php - 如何在 php 中使用 in_array 并将数组作为针,但在至少有一个值匹配时返回 true

json - Grails,从具有多关系的json字符串创建域对象

php - 使用 Android 将 Http 发布到服务器 json

json - 如何使用 cl-json 库将 json-string 转换为 CLOS 对象?

ruby - 如何在数组数组中获取特定值

python - 与常规 Python 列表相比,NumPy 有哪些优势?

php - 如何在 foreach 中取消设置上一个数组元素

java - 将文件中的每一行读入其自己的不同二维数组中

javascript - JSON 字符串转 JS 数组