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

查看:208
本文介绍了具有多维和多类型数组的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,并且我只将String转换为值var values: [[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天全站免登陆