gpt4 book ai didi

swift4 - Swift 4 使用 Codable 解码 json

转载 作者:行者123 更新时间:2023-12-04 11:34:02 25 4
gpt4 key购买 nike

有人能告诉我我做错了什么吗?我已经查看了这里的所有问题,例如从这里 How to decode a nested JSON struct with Swift Decodable protocol?我找到了一个看起来正是我需要的 Swift 4 Codable decoding 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: "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)
}

关于swift4 - Swift 4 使用 Codable 解码 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com