且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift 4使用Codable解码json

更新时间:2021-10-19 18:14:43

JSON文本的概述结构:

Check the outlined structure of your JSON text:

{
    "success": true,
    "message": "got the locations!",
    "data": {
      ...
    }
}

数据 的值是JSON对象 {...} ,它不是数组。
对象的结构:

The value for "data" is a JSON object {...}, it is not an array. And the structure of the object:

{
    "LocationList": [
      ...
    ]
}

对象只有一个条目 LocationList:[...] ,其值为数组 [...]

The object has a single entry "LocationList": [...] and its value is an array [...].

您可能还需要一个结构:

You may need one more struct:

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)
}