2016-12-20 13 views
0

私は以下のjsonを持っていますが、Swift 3でそれを解析する方法を理解することはできません。 APIのjsonには配列のルートがあります。私はSwift 4とAlamofire 4.0でXcode 8.2.1を使用しています。Swson 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) 
    } 
} 

here示唆したように、私はこのlet item = readableJSON["items"] as? [[String: Any]]を試してみましたが、それは誤り[String:Any] has no subscriptでコンパイルされないだろうとlet item = readableJSON["items"] as? [String: Any]!が警告Expression implicitly coerced from stringでコンパイルが、nilを生成します。このjsonを解析することは私の生死です。

+0

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

+0

私はそれを読み、多分I私はちょうどばかだけど、私は私と一致するjsonパターンを見つけることができず、2日後に私はここに来た。 – markhorrocks

+1

ヒント(実際にはほぼ完全な解決策です): "items"は配列を含む辞書です。この配列には辞書が含まれています。 //終わりです。 – Moritz

答えて

0

をこれは私が最終的に思い付いた解析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! 
} 
2

は、あなたがそうのようにその辞書に要素にアクセスできるようになります

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

のようなものを実行します。

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

"index"や "price"を使ってみましたが、エラー ''型の値をキャストできませんでした '' __NSArrayM '(0x10c60ddb0)から' NSString '(0x10bc14c40) 'に変更します。 – markhorrocks

+1

ああ、まあ、あなたのタイプにあなたのキャストを一致させる必要があるように聞こえる。 –

0

Alamofire例スウィフト3でJSONのためのあなたのproject.Use SwiftyJSONへのすべての利用2 cocoapodsの

1.Firstは解析

pod 'Alamofire' 
pod 'SwiftyJSON' 
  1. My Jsonが下にあります

    { "loginNodes":[{ "にErrorMessage": "Alamofireへようこそ"、 "名前":エナマル・ハク、 "のerrorCode": "0"、 "写真":ヌル}]}

  2. それ異なる方法で行うことができます。しかし私はWayの下でやった。サーバを送信するためのパラメータが必要ない場合は、パラメータオプションを削除してください。それはポストやメソッドを取得することがあります。どのような方法でも使用できます。マイ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 = [文字列:ANYOBJECT]((responseDa場合

  5. ような配列に値を割り当てますta.result.value!= NIL))taleView、cellForRowAt indexPathにおいて{

      // 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. 、ちょうど

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

を使用スウィフト3 スイフト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 
} 

}

関連する問題