Swift 4使用Codable解码json

米莎

有人可以告诉我我在做什么错吗?我已经从这里开始研究了这里的所有问题,如何使用Swift Decodable协议解码嵌套的JSON结构?并且我发现了一个似乎正是我需要Swift 4 Codable解码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:“预期对Array进行解码,但找到了字典。”,underlyingError:nil))

OOPer

检查JSON文本的概述结构:

{
    "success": true,
    "message": "got the locations!",
    "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,
    "message": "got the locations!",
    "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)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章