简体   繁体   English

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

[英]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. 我下面有json,但无法弄清楚如何在Swift 3中解析它。我的代码如下。 The json from the API has an array root. API中的json具有数组根。 I am using Xcode 8.2.1 with Swift 4 and Alamofire 4.0. 我在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;
...

Here is my code. 这是我的代码。 I have tried to get an array r dictionary from the results but it's always nil. 我试图从结果中获取数组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)
    }
}

I have tried this let item = readableJSON["items"] as? [[String: Any]] 我已经尝试过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]]如此处建议但不会编译错误[String:Any] has no subscript并且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. Expression implicitly coerced from string警告Expression implicitly coerced from string编译,但产生nil。 Parsing this json is life or death for me. 解析这个json对我来说是生是死。

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. 这是我最终想到的解析json函数。 The problem for this json data is that it is a dictionary inside an array. 此json数据的问题在于它是数组内的字典。 I am a noob and most of the answers and how tos I saw would not fit my json data. 我是一个菜鸟,大多数答案以及我看到的方法都不适合我的json数据。 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 Swift 3中的Alamofire示例

1.First of all Use two cocoapods to your project.Use SwiftyJSON for json parse 1,首先在项目中使用两个cocoapods,使用SwiftyJSON进行json解析

pod 'Alamofire'
pod 'SwiftyJSON'
  1. My Json is below 我的杰森在下面

    {"loginNodes":[{"errorMessage":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]} {“ loginNodes”:[{“ errorMessage”:“欢迎来到Alamofire”,“名称”: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代码在下面...对我来说很好...

      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] var arrRes = [String:AnyObject]

  5. Assign the value to array like 将值分配给数组,例如

    if((responseData.result.value != nil)){ 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 在taleView中,cellForRowAt indexPath,只需使用

      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 Swift 3中的Swift 3 Alamofire示例

import UIKit import Alamofire import SwiftyJSON 导入UIKit导入Alamofire导入SwiftyJSON

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { 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