在 Swift/Xcode 中将 JSON 文件转换为数组 [英] Turning JSON file into an array in Swift/Xcode
问题描述
我整个星期都在挣扎.我是编程新手.我无法在 Xcode 中将简单的 JSON 文件转换为字典.几乎没有使用 Codable 新方法的在线简化文档.所以我正在使用演练,其中包含以下代码.
I have been struggling all week. I am new to programming. I cannot turn a simple JSON file into a dictionary in Xcode. There is little simplified documentation online using the new method of Codable. So I am using a walkthrough, which has the following code.
导入 UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let path = Bundle.main.path(forResource: "menu", ofType: "json") else { return }
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
//print(json)
guard let array = json as? [Any] else { return }
for user in array {
guard let userDict = user as? [String: Any] else { return }
guard let drinks = userDict["drinks"] as? String else { print("not a String"); return }
guard let junkFood = userDict["junk-food"] as? String else { return }
print(drinks)
print(junkFood)
print(" ")
}
}
catch {
print(error)
}
}
}
The below code is what my JSON looks like.
{"menu": {
"drinks": [
{"coke": "20"},
{"pepsi": "20"},
{"water": "20"}
],
"junk-food": [
{"hamburger": "40"},
{"fries": "20"},
{"pizza": "20"}
]
}}
任何人都可以请教我,或者向我展示一些关于如何将 JSON 转换为字典以便我以后可以从中映射数据的简化文档吗?我正在使用 Xcode 并尝试使用 Swift 4.
Can anyone please walk me through, or show me some simplified documentation as to how I can turn the JSON into a dictionary that I can later map the data from? I am using Xcode and trying to work out Swift 4.
预先感谢您的耐心等待.
Thanks in advance for your patience.
推荐答案
我猜你的 json 实际上是一个字典而不是一个数组.所以 guard let array = json as?[Any] else { return }
失败了,因为 json 是 [String: Any]
.您可以使用 "menu"
键访问数组.
My guess is that your json is actually a Dictionary not an Array. So guard let array = json as? [Any] else { return }
is falling through because the json is [String: Any]
. You can get to the array with the "menu"
key.
这是您的代码的更新版本:
Here's an updated version of your code:
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
//print(json)
guard let menuDict = json as? [String: Any] else { return }
guard let drinks = menuDict["drinks"] as? [[String: Any]] else {
print("not an array of dictionaries")
return
}
guard let junkFood = menuDict["junk-food"] as? [[String: Any]] else {
print("not an array of dictionaries")
return
}
print(drinks)
print(junkFood)
print(" ")
}
试试看,让我知道它是否有效.顺便说一下,这只是 do 块.
Try that, let me know if it works. This is just the do block by the way.
这篇关于在 Swift/Xcode 中将 JSON 文件转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!