{"success": true,"message": "got the locations!","data": { "LocationList": [ { "LociD": 1,"Locname": "Downtown" },{ "LociD": 2,"Locname": "Uptown" },{ "LociD": 3,"Locname": "MIDtown" } ] }}struct Location: Codable { var data: [LocationList]}struct LocationList: Codable { var LociD: Int! var Locname: String!}class VIEwController: UIVIEwController {overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() let url = URL(string: "/getlocationList") let task = URLSession.shared.dataTask(with: url!) { data,response,error in guard error == nil else { print(error!) return } guard let data = data else { print("Data is empty") return } do { let locList = try JsONDecoder().decode(Location.self,from: data) print(locList) } catch let error { print(error) } } task.resume()}
我得到的错误是:
检查JsON文本的概述结构:typeMismatch(Swift.Array,Swift.DeCodingError.Context(CodingPath:
[],deBUGDescription: “Expected to decode Array but found a
dictionary instead.”,underlyingError: nil))
{ "success": true,"data": { ... }}
“data”的值是JsON对象{…},它不是数组.
和对象的结构:
{ "LocationList": [ ... ]}
该对象有一个单独的条目“LocationList”:[…],它的值是一个数组[…].
您可能还需要一个结构:
struct Location: Codable { var data: LocationData}struct LocationData: Codable { var LocationList: [LocationItem]}struct LocationItem: Codable { var LociD: Int! var Locname: String!}
用于检测…
var JsonText = """{ "success": true,"data": { "LocationList": [ { "LociD": 1,"Locname": "Downtown" },{ "LociD": 2,"Locname": "Uptown" },{ "LociD": 3,"Locname": "MIDtown" } ] }}"""let data = JsonText.data(using: .utf8)!do { let locList = try JsONDecoder().decode(Location.self,from: data) print(locList)} catch let error { print(error)}总结
以上是内存溢出为你收集整理的swift4 – Swift 4使用Codable解码json全部内容,希望文章能够帮你解决swift4 – Swift 4使用Codable解码json所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)