Swift 4使用Codable解码json

Mis*_*sha 7 swift4 codable

有人能告诉我我做错了什么吗?我在这里查看了所有问题,如下所示如何使用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()
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:"预计会解码数组,但会找到一个字典.",underlyingError:nil))

OOP*_*Per 8

检查JSON文本的概述结构:

{
    "success": true,
    "message": "got the locations!",
    "data": {
      ...
    }
}
Run Code Online (Sandbox Code Playgroud)

值为"data"JSON对象{...},它不是数组.和对象的结构:

{
    "LocationList": [
      ...
    ]
}
Run Code Online (Sandbox Code Playgroud)

该对象具有单个条目"LocationList": [...],其值为数组[...].

您可能还需要一个结构:

struct Location: Codable {
    var data: LocationData
}

struct LocationData: Codable {
    var LocationList: [LocationItem]
}

struct LocationItem: Codable {
    var LocID: Int!
    var LocName: String!
}
Run Code Online (Sandbox Code Playgroud)

用于检测...

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)
}
Run Code Online (Sandbox Code Playgroud)