简体   繁体   中英

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

I have the json below but unable to figure out how to parse it in Swift 3. My code is below. The json from the API has an array root. I am using Xcode 8.2.1 with Swift 4 and Alamofire 4.0.

["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;
...

Here is my code. I have tried to get an array r dictionary from the results but it's always nil.

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)
    }
}

I have tried this let item = readableJSON["items"] as? [[String: Any]] let item = readableJSON["items"] as? [[String: Any]] as suggested here but it would not compile with an error [String:Any] has no subscript and let item = readableJSON["items"] as? [String: Any]! let item = readableJSON["items"] as? [String: Any]! compiles with a warning Expression implicitly coerced from string but produces nil. Parsing this json is life or death for me.

Do something like

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

then you'll be able to access elements in that dictionary like so:

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

This was the parse json function I eventually came up with. The problem for this json data is that it is a dictionary inside an array. I am a noob and most of the answers and how tos I saw would not fit my json data. Here is the function I finally came up with with worked.

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

then in my view controller class

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!
}

Alamofire Example in Swift 3

1.First of all Use two cocoapods to your project.Use SwiftyJSON for json parse

pod 'Alamofire'
pod 'SwiftyJSON'
  1. My Json is below

    {"loginNodes":[{"errorMessage":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}

  2. It may be done in different way. But I have done below Way. Note if you don't need any parameter to send the server then remove parameter option. It may work post or get method. You can use any way. My Alamofire code is below...which is working fine for me......

      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. If You use Like table View Or Collection View or so on, you can use like that..

  4. Declare A Array

    var arrRes = [String:AnyObject]

  5. Assign the value to array like

    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. In taleView, cellForRowAt indexPath , Just use

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

Swift 3 Alamofire Example in Swift 3

import UIKit import Alamofire import SwiftyJSON

class 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
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM