我正试图返回字典字符串值。它返回为:
类别:[yelp1.Zom2(类别:yelp1.Zom3(名称:“Delivery”))、yelp1.Zom2(类别:yelp1.Zom3(名称:“Dine out”)…]
如何只返回名称值,如“Delivery”和“Dine Out”?
//yelp1只是文件名
示例JSON数据
{
"categories": [
{
"categories": {
"id": 1,
"name": "Delivery"
}
},
{
"categories": {
"id": 2,
"name": "Dine-out"
}
},
这些是我的结构
struct Zom3:Codable{
let name:String
}
struct Zom2:Codable{
//let category_id:Int?
let categories: Zom3
}
struct Zom:Codable{
//let category_id:Int?
let categories: [Zom2]
}
我试图解码Zom3,因为这是名称值所在的位置,但它表示找不到密钥。它不允许我使用for循环进行迭代,以至少逐个获取字典中的每个元素。
override func viewDidLoad() {
super.viewDidLoad()
let urlName = "https://developers.zomato.com/api/v2.1/categories"
let url = URL(string: urlName)
var urlReq = URLRequest(url: url!)
urlReq.httpMethod = "GET"
urlReq.addValue("application/json", forHTTPHeaderField: "Accept")
urlReq.addValue(zomatoKey, forHTTPHeaderField: "user_key")
let task = URLSession.shared.dataTask(with: urlReq) { (data, response, error) in
guard let data = data else {return}
do {
let items = try JSONDecoder().decode( Zom.self, from: data)
print(items)
}
catch {
print(error)
}
}
task.resume()
}
最佳答案
从你所写的来看,你的输出似乎来自你的“打印(项目)”行。如果这是真的,那么您称之为“items”的对象是顶级结构“Zom”。要获得最底层的“name”,我认为您确实需要在“let items=try…”;下使用for循环(而不是“print(items)”
var arrayOfNames: [String] = []
let zoms = item.categories
for item in zoms {
let possibleName = item.categories?.name
if let name = possibleName {
arrayOfNames.append(name)
}
}
print(arrayOfNames)
若我并没有犯任何错误,这将创建一个名称数组并打印出“送货,外出就餐”
关于arrays - 我将如何分隔JSON字典值并将其放入Swift数组中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55859744/