7

有人可以告诉我我做错了什么吗?我已经查看了这里的所有问题,比如从这里如何使用 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 但找到了一个字典。",底层错误: nil))

4

3 回答 3

8

检查 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)
}
于 2017-09-16T08:50:16.127 回答
0

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

let jsonString = object.toJSONString(prettyPrint: true)
print(jsonString as AnyObject)
于 2019-11-04T09:19:14.333 回答
0

关于 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."
 }
*/
于 2020-10-01T11:58:43.580 回答