【问题标题】:Extracting values from Json Data in Swift iOS9在 Swift iOS9 中从 Json 数据中提取值
【发布时间】:2017-04-05 20:05:20
【问题描述】:

我从服务器检索到以下 JSon 数据,我想提取值名称并将它们作为模型存储在数组或字典中。问题是返回的值本身是另一个字典的形式。我如何提取频率、描述和数量的值并将它们更新到我的表格视图。下面是我从服务器请求中获得的 Json 数据格式。我是 swift 新手,字典和数组的概念让我很困惑

{
"payment" =     (
            {
        amount = 100;
        currency = USD;
        description = "Awesome Videos";
        frequency = Day;
    },
            {
        amount = 500;
        currency = USD;
        description = "Awesome Videos";
        frequency = Week;
    },
            {
        amount = 3000;
        currency = USD;
        description = "Awesome Videos";
        frequency = Months;
    }
);

}

我想将它们本地存储在字典或数组中,并将它们更新到我的 tableview。

这也是我从服务器获取数据的代码

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
        if (data != nil){
            print(data)
            do {

                // let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers)
                let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

                print(jsonResult)
                print(jsonResult["payment_plans"])



                if let plan_list = jsonResult as? NSDictionary{
                    print("got dictionary")

                    for (key, value) in plan_list
                    {
                        print(value)
                        print("printing keys")
                        print(key)

                        if let plans = value as? NSDictionary
                        {
                            print("printing values")
                            print(plans)
                            print(plans["currency"])
                        }
                    }
                }

            }   catch{
                print("Json Serialization failed")
            }
        }

    }
    /*
    if (response != nil){
    print(response)
    }
    else{
    print(error)
    }
    }
    */
    task.resume()
}

我被困在这里如何提取我在字典中得到的值。提前致谢

【问题讨论】:

    标签: ios json uitableview dictionary


    【解决方案1】:

    您好,您可以按以下方式迭代您的结果:

    if((jsonResult) != nil) {
        let swiftyJsonVar = jsonResult!
        do {
           if let dicObj = swiftyJsonVar as? NSDictionary {
               print("Response is dictionary")
               print(dicObj)
               let arrObj = dicObj["payment"] as NSArray
                // Then iterate your arrObj and do as per your need.
                //for eg.
               arrObj[0]["description"]
            }
        }
    }
    

    【讨论】:

    • 这会返回一个致命错误“在展开可选值时意外发现 nil”,'dicObj["payment"]' 返回 nil
    • 你可以像这样使用.. dicObj["payment"] as! NSArray
    • 我让它工作了......谢谢,你能推荐我如何在 tableviewcell 中填充上述数据吗?它似乎对我不起作用。这是我的代码func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("choosePlan", forIndexPath: indexPath) as!UITableViewCell cell.textLabel?.text = PlanStorage[indexPath.row] return cell }
    • 您可以像这样使用在您的单元格上显示值..... cell.textLabel?.text = PlanStorage[indexPath.row] [description]
    • 在分配给单元格之前请检查密钥,因为它可能为零。如果它为零,那么它可能会崩溃。所以请检查一下....
    【解决方案2】:

    字典是 key-value 存储,在您的情况下,值具有 AnyObject 类型。

    要将数据转换为DictionaryArray,您可以使用

    let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    

    然后创建支付数组

    if let payments = jsonResult as? Array{ 
    
         *iterate here all payments 
    
    }
    

    如果您想使用for (key, value) in plan_list,您需要将其更改为for (key, value) in plan_list.enumerate()

    【讨论】:

    • 我设法获得了 Json 数据....知道如何将数据填充到 tableview 中吗?似乎对我不起作用。谢谢
    • 在您的班级中创建一个属性payments
    • 抱歉,然后将所有数据放入 payments 属性并在表视图 dataSource 方法中调用 reloadData() 您可以使用 'if let payment = self.payments as? NSDictionary { cell.label.text = payment["description"] as? String}' 别忘了你还有一个整数!
    • 我尝试在每个数据源方法中调用 reloadData self.PlanStorage.append(display_price) self.PlanStorage.append(display_name) 这里 PlanStoage 是存储数据的位置,并且是一个字符串数组。 ` cell.textLabel?.text = PlanStorage[indexPath.row] ` 这是填充数据的代码,但不起作用
    • func numberOfSectionsInTableView(tableView: UITableView) -> Int { tableView.reloadData() return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.reloadData() return PlanStorage.count }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多