簡體   English   中英

如何在Swift 3中使用Alamofire 4解析此json?

[英]How to parse this json with Alamofire 4 in Swift 3?

我下面有json,但無法弄清楚如何在Swift 3中解析它。我的代碼如下。 API中的json具有數組根。 我在Swift 4和Alamofire 4.0中使用Xcode 8.2.1。

["items": <__NSArrayM 0x608000248af0>(
{
    currency = USD;
    image = "https://cdn.myDomain.com/image.jpg";
    "item_title" = "Antique Table";
    "name:" = "";
    price = 675;
},
{
    currency = USD;
    image = "https://cdn.mydomain.com/image2.jpg";
    "name:" = "";
    price = 950;
...

這是我的代碼。 我試圖從結果中獲取數組r字典,但它始終為零。

Alamofire.request(myURL)
    .responseJSON(completionHandler: {
        response in
        self.parseData(JSONData: response.data!)
    })
}

func parseData(JSONData: Data) {

    do {
        let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.mutableContainers) as! [String: Any] 
        print(readableJSON)               
    }
    catch {
     print(error)
    }
}

我已經嘗試過let item = readableJSON["items"] as? [[String: Any]] let item = readableJSON["items"] as? [[String: Any]]如此處建議但不會編譯錯誤[String:Any] has no subscript並且let item = readableJSON["items"] as? [String: Any]! let item = readableJSON["items"] as? [String: Any]! Expression implicitly coerced from string警告Expression implicitly coerced from string編譯,但產生nil。 解析這個json對我來說是生是死。

做類似的事情

let responseJSON = response.result.value as! [String:AnyObject]

那么您將能夠像這樣訪問該詞典中的元素:

let infoElementString = responseJSON["infoElement"] as! String

這是我最終想到的解析json函數。 此json數據的問題在於它是數組內的字典。 我是一個菜鳥,大多數答案以及我看到的方法都不適合我的json數據。 這是我最后想出的功能。

var myItems = [[String:Any]]()

然后在我的視圖控制器類中

func loadMyItems() {

    Alamofire.request(myItemsURL)
        .responseJSON(completionHandler: {
            response in                
            self.parseData(JSONData: response.data!)

            self.collectionView.reloadData()                
        })
}

func parseData(JSONData: Data) {        
        do {                
            let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.allowFragments) as! [String: Any]

            let items = readableJSON["items"] as! [[String: Any]]

            self.myItems = items

 }               
        catch {
         print(error)
        }
}


func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as? myCell

    let dictionary = myItems[indexPath.row] as [String:Any]
    if let item_title = dictionary["item_title"] as? String {
        cell!.textLabel.text = item_title
        print(item_title)
    }

    return cell!
}

Swift 3中的Alamofire示例

1,首先在項目中使用兩個cocoapods,使用SwiftyJSON進行json解析

pod 'Alamofire'
pod 'SwiftyJSON'
  1. 我的傑森在下面

    {“ loginNodes”:[{“ errorMessage”:“歡迎來到Alamofire”,“名稱”:Enamul Haque,“ errorCode”:“ 0”,“ photo”:null}]}

  2. 可以以不同的方式來完成。 但是我已經做了下面的方式。 請注意,如果您不需要任何參數來發送服務器,請刪除參數選項。 它可能會發布或獲取方法。 您可以使用任何方式。 我的Alamofire代碼在下面...對我來說很好...

      Alamofire.request("http://era.com.bd/UserSignInSV", method: .post,parameters:["uname":txtUserId.text!,"pass":txtPassword.text!]).responseJSON{(responseData) -> Void in if((responseData.result.value != nil)){ let jsonData = JSON(responseData.result.value) if let arrJSON = jsonData["loginNodes"].arrayObject { for index in 0...arrJSON.count-1 { let aObject = arrJSON[index] as! [String : AnyObject] let errorCode = aObject["errorCode"] as? String; let errorMessage = aObject["errorMessage"] as? String; if("0"==errorCode ){ //Database Login Success Action }else{ // //Database Login Fail Action } } } } } 
  3. 如果您使用“贊”表視圖或“集合視圖”等,則可以這樣使用。

  4. 聲明一個數組

    var arrRes = [String:AnyObject]

  5. 將值分配給數組,例如

    if((responseData.result.value!= nil)){

      // let jsonData = JSON(responseData.result.value) if((responseData.result.value != nil)){ let swiftyJsonVar = JSON(responseData.result.value!) if let resData = swiftyJsonVar["loginNodes"].arrayObject { self.arrRes = resData as! [[String:AnyObject]] } if self.arrRes.count > 0 { self.tableView.reloadData() } } } 
  6. 在taleView中,cellForRowAt indexPath,只需使用

      let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customCell cell.errorLabelName.text = arrRes[indexPath.row]["errorMessage"] as? String 

Swift 3中的Swift 3 Alamofire示例

導入UIKit導入Alamofire導入SwiftyJSON

ViewController類:UIViewController,UITableViewDelegate,UITableViewDataSource {

var array = [[String:AnyObject]]()

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    Alamofire.request("http://www.designer321.com/johnsagar/plumbingapp/webservice/list_advertise.php?zip=123456").responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil)
        {
            let swiftyJsonVar = JSON(responseData.result.value!)
            print("Main Responce")
            print(swiftyJsonVar)
       }
        if let result = responseData.result.value
        {
           if let Res = (result as AnyObject).value(forKey: "response") as? NSDictionary
            {
                if let Hallo = (Res as AnyObject).value(forKey: "advertise_list") as? NSArray
                {
                    print("-=-=-=-=-=-=-")
                    print(Hallo)

                    self.array = Hallo as! [[String:AnyObject]]
                    print(self.array)


                }

            }
            self.tableview.reloadData()
        }


    }



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return array.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
     let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell

    var dict = array[indexPath.row]
    cell.lbl1.text = dict["address"] as? String
    cell.lbl2.text = dict["ad_created_date"] as? String
    cell.lbl3.text = dict["phone_number"] as? String
    cell.lbl4.text = dict["id"] as? String
    cell.lbl5.text = dict["ad_zip"] as? String

    let imageUrlString = dict["ad_path"]
    let imageUrl:URL = URL(string: imageUrlString as! String)!
    let imageData:NSData = NSData(contentsOf: imageUrl)!
    cell.img.image = UIImage(data: imageData as Data)



    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return 100
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM