Swift 4 使用 Codable 解码 json

Swift 4 decoding json using Codable

有人可以告诉我我做错了什么吗?我从这里 and I've found one that seems exactly what I need .

查看了这里的所有问题
{
"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,
    "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)
}

在互联网上搜索了很多东西之后,我当然发现这是从任何对象打印格式良好 json 的最甜蜜方式。

let jsonString = object.toJSONString(prettyPrint: true)
print(jsonString as AnyObject)

关于 JSONEncoder 的 Apple 文档 ->

struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)

/* Prints:
 {
   "name" : "Pear",
   "points" : 250,
   "description" : "A ripe pear."
 }
*/