gpt4 book ai didi

json - Swift 将 json 数据获取到结构中并填充 pickerViews

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

我正在编写一个应用程序,我想用汽车品牌和汽车型号填充 2 个依赖的 UIPickerView。

我正在解析输入中的以下 json 文件,其中包含汽车模型的输入:

[{
"brand": "ALFA ROMEO",
"models": [
"Mito (145)",
"145/146 (930)",
"147 (937)",
"Giulietta (940)",
"155 (167)",
"156 (932)",
"159 (939)",
"Giulia (620)",
"164 (164)",
"166 (136)",
"GTV / Spider (916)",
"Brera",
"Spider (939)",
"GT Coupé (937)",
"4C (643)",
"Stelvio (630)"
]},
{
"brand": "AMC",
"models": [
"Alliance",
"Concord",
"Eagle",
"Encore",
"Spirit"
]
},
...
]

我想获取前 UIPickerView 上的汽车品牌列表并根据用户对前者的选择来提供后者...

我使用以下结构来解析并获取jsondata

struct carBrands : Codable {
let brand : String
let models : [String]
}

这个函数允许我解析 json 并获取cars 对象取决于结构

var cars:carBrands?

这里是 json 解码器

let url = Bundle.main.url(forResource: "carModels", withExtension: "json")
/*let jsonData = try? Data(contentsOf: url!)
let jsonResponse = try? JSONSerialization.jsonObject(with: jsonData!)*/

URLSession.shared.dataTask(with: url!) { (data, response
, error) in

guard let data = data else { return }
do {
let decoder = JSONDecoder()
let carData = try decoder.decode(carBrands.self, from: data)
print(carData)
self.cars = carData
return
}catch let err {
print("Err", err)
}
}.resume()

我在 xcode 上遇到此错误

Err typeMismatch(Swift.Dictionary<Swift.String, Any>,     Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

您能展示一下正确填充我的 uipickerviews 的技巧吗?

谢谢。

最佳答案

现在,我的 self.cars 上有这个数组

▿ Optional<Array<carBrands>>
▿ some : 70 elements
▿ 0 : carBrands
- brand : "ALFA ROMEO"
▿ models : 16 elements
- 0 : "Mito (145)"
- 1 : "145/146 (930)"
- 2 : "147 (937)"
- 3 : "Giulietta (940)"
- 4 : "155 (167)"
- 5 : "156 (932)"
- 6 : "159 (939)"
- 7 : "Giulia (620)"
- 8 : "164 (164)"
- 9 : "166 (136)"
- 10 : "GTV / Spider (916)"
- 11 : "Brera"
- 12 : "Spider (939)"
- 13 : "GT Coupé (937)"
- 14 : "4C (643)"
- 15 : "Stelvio (630)"
▿ 1 : carBrands
- brand : "AMC"
▿ models : 5 elements
- 0 : "Alliance"
- 1 : "Concord"
- 2 : "Eagle"
- 3 : "Encore"
- 4 : "Spirit"
▿ 2 : carBrands
- brand : "Aston Martin"
▿ models : 9 elements
- 0 : "DB7"
- 1 : "DB9"
- 2 : "DBS"
- 3 : "Lagonda"
- 4 : "Rapide"
- 5 : "V12 Vantage"
- 6 : "V8 Vantage"
- 7 : "Vanquish"
- 8 : "Virage"

我必须将所有汽车品牌列入列表,然后按照用户的选择用汽车型号填充另一个选择器。你能告诉我该怎么做吗?

对不起,我是初学者。感谢您抽出时间来回答。 :)

关于json - Swift 将 json 数据获取到结构中并填充 pickerViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888352/

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