swift4 – Swift 4使用Codable解码json

swift4 – Swift 4使用Codable解码json,第1张

概述有人能告诉我我做错了什么吗?我已经看过这里的所有问题,就像从这里 How to decode a nested JSON struct with Swift Decodable protocol?一样,我发现了一个看起来正是我需要的东西 Swift 4 Codable decoding json. {"success": true,"message": "got the locations!" 有人能告诉我我做错了什么吗?我已经看过这里的所有问题,就像从这里 How to decode a nested JSON struct with Swift Decodable protocol?一样,我发现了一个看起来正是我需要的东西 Swift 4 Codable decoding json.
{"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()}

我得到的错误是:

typeMismatch(Swift.Array,Swift.DeCodingError.Context(CodingPath:
[],deBUGDescription: “Expected to decode Array but found a
dictionary instead.”,underlyingError: nil))

检查JsON文本的概述结构:
{    "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所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1041690.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存