SwiftyJson解析oData响应

时间:2017-12-04 15:07:57

标签: swift odata swifty-json

我正在尝试使用SwiftyJSON解析oData Web服务

这是我的oData回复:

{
  "odata.metadata":"http://url.com/odata/$metadata#Updates","value":[
    {
      "ID":1,"msgTitle":"Testing","reportedBy":"testUser"
    }

  ]
}  

这是我的Swift代码:

 Alamofire.request(URL, method: .get).responseString { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                self.activityIndicator.stopAnimating()
                let swiftyJsonVar = JSON(responseData.result.value!)
                print(swiftyJsonVar)
                if let resData = swiftyJsonVar["value"].arrayObject {
                    if let dict = resData as? [Dictionary<String, AnyObject>] {
                        for obj in dict {
                            let announce = announcement(fileDict: obj)
                            self.Announcements.append(announce)
                        }

                        self.tableView.reloadData()
                        self.tableView.isHidden = false
                    }
                }
            }
        }

问题是resData返回null。在值数组中获取JSON我做错了什么?

我也尝试过swiftyJsonVar [0] [“value”]。arrayObject没有成功。

1 个答案:

答案 0 :(得分:0)

在查阅了swiftyJSON文档后,我能够使用以下语法解决这个问题:

Alamofire.request(URL, method: .get).responseString { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                self.activityIndicator.stopAnimating()
                //log.info("Response: \(responseData.result.value)")
                let jsonObj = responseData.result.value!
                if let dataFromString = jsonObj.data(using: .utf8, allowLossyConversion: false) {
                    let json = JSON(data: dataFromString)
                    print(json)
                    if let resData = json["value"].arrayObject {
                        if let dict = resData as? [Dictionary<String, AnyObject>] {
                            for obj in dict {
                                let announce = announcement(fileDict: obj)
                                self.Announcements.append(announce)
                            }

                            self.tableView.reloadData()
                            self.tableView.isHidden = false
                        }
                    }
                }
            }
        }