加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift4 – Swift 4使用Codable解码json

发布时间:2020-12-14 05:38:27 所属栏目:百科 来源:网络整理
导读:有人能告诉我我做错了什么吗?我已经看过这里的所有问题,就像从这里 How to decode a nested JSON struct with Swift Decodable protocol?一样,我发现了一个看起来正是我需要的东西 Swift 4 Codable decoding json. {"success": true,"message": "got the lo
有人能告诉我我做错了什么吗?我已经看过这里的所有问题,就像从这里 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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读