我将如何分隔JSON字典值并将其放入Swift数组中?

时间:2019-04-26 01:47:01

标签: arrays json swift dictionary

我正在尝试返回字典字符串值。它返回为:

  

类别:[yelp1.Zom2(类别:yelp1.Zom3(名称:“交付”)),yelp1.Zom2(类别:yelp1.Zom3(名称:“外出”))。...]

如何只返回名称名称,例如“ 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()
}

1 个答案:

答案 0 :(得分:0)

根据您所写的内容,看起来您的输出来自“ print(items)”行。如果是这样,那么您称为“ items”的对象就是顶层结构“ Zom”。为了获得最底层的“名称”,我认为您确实需要在“ 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)

如果我没有记错的话,应该创建一个名称数组并打印出“ Delivery,Dine-Out”