2016-12-20 109 views
0

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

["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]]的建議here,但它不會有錯誤[String:Any] has no subscript編譯和let item = readableJSON["items"] as? [String: Any]!編譯一個警告Expression implicitly coerced from string但產生爲零。解析這個json對我來說是生死攸關的。

+0

研究這個:https://developer.apple.com/swift/blog/?id=37 – Moritz

+0

我讀了,也許我只是啞巴,但我找不到與我的相匹配的json模式,並且在我來到這裏2天后。 – markhorrocks

+1

這是一個提示(實際上幾乎是一個完整的解決方案):「items」是一個包含數組的字典。該數組包含字典。 //結束,完成。 – Moritz

回答

0

這是解析JSON功能,我終於想出了。這個json數據的問題在於它是一個數組中的字典。我是一個noob,大部分答案和我看到的不適合我的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! 
} 
2

這樣做

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

,那麼你就可以訪問元素在字典中,像這樣:

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

我試圖使用「索引」或「價格」,但得到錯誤「無法轉換類型的值'__NSArrayM '(0x10c60ddb0)到'NSString'(0x10bc14c40)'。 – markhorrocks

+1

啊,好吧,聽起來你需要將你的演員配合你的類型。 –

0

Alamofire實例斯威夫特3

所有使用兩的CocoaPods您project.Use SwiftyJSON對JSON 1.首先解析

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

    { 「loginNodes」:[{ 「的errorMessage」: 「歡迎來到Alamofire」, 「姓名」:納馬爾·哈克 「的errorCode」: 「0」, 「照片」:空}]}

  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. 聲明一個陣列

    變種arrRes = [字符串:AnyObject]

  5. 分配值,以陣列狀

    如果((responseDa ta.result.value!=無)){

      // 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 
    
0

夫特3 Alamofire實施例中夫特3

進口的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 
} 

}