Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Swift 3中的Alamofire 4解析这个json?_Json_Swift_Alamofire - Fatal编程技术网

如何用Swift 3中的Alamofire 4解析这个json?

如何用Swift 3中的Alamofire 4解析这个json?,json,swift,alamofire,Json,Swift,Alamofire,我有下面的json,但无法理解如何在Swift 3中解析它。我的代码如下。API中的json有一个数组根。我将Xcode 8.2.1与Swift 4和Alamofire 4.0一起使用 ["items": <__NSArrayM 0x608000248af0>( { currency = USD; image = "https://cdn.myDomain.com/image.jpg"; "item_title" = "Antique Table";

我有下面的json,但无法理解如何在Swift 3中解析它。我的代码如下。API中的json有一个数组根。我将Xcode 8.2.1与Swift 4和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;
...
我试过这个
let item=readableJSON[“items”]作为?[[String:Any]]
如建议的那样,但它不会编译,并出现错误
[String:Any]没有下标
并且
让item=readableJSON[“items”]as?[字符串:任意]编译时带有一个从字符串隐式强制的警告
表达式,但生成nil。解析这个json对我来说是生死攸关的。

像这样做吧

让responseJSON=response.result.value为![字符串:AnyObject]

然后您将能够访问该字典中的元素,如下所示:

let infoElementString = responseJSON["infoElement"] as! String
做点像

让responseJSON=response.result.value为![字符串:AnyObject]

然后您将能够访问该字典中的元素,如下所示:

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

这就是我最终提出的parse 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!
}

这就是我最终提出的parse 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!
}

Swift 3中的阿拉莫菲尔示例

1.首先,在项目中使用两个CoCoapod。使用SwiftyJSON进行json解析

pod 'Alamofire'
pod 'SwiftyJSON'
  • 我的Json在下面

    {“loginNodes”:[{“errorMessage”:“欢迎来到阿拉莫菲尔”,“姓名”:Enamul Haque,“错误代码”:“0”,“照片”:null}]}

  • 可以用不同的方式来做。但我做了下面的事情。注意:如果发送服务器不需要任何参数,请删除参数选项。它可以工作岗位或获取方法。你可以用任何方法。我的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
                        }
                    }
    
    
                }
            }
       }
    
  • 如果使用类似表视图或集合视图等,则可以使用类似

  • 声明数组

    var arrRes=[String:AnyObject]

  • 将值赋给数组,如

    如果((responseData.result.value!=nil)){

  • 在taleView中,cellForRowAt indexPath只需使用

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

  • Swift 3中的阿拉莫菲尔示例

    1.首先,在项目中使用两个CoCoapod。使用SwiftyJSON进行json解析

    pod 'Alamofire'
    pod 'SwiftyJSON'
    
  • 我的Json在下面

    {“loginNodes”:[{“errorMessage”:“欢迎来到阿拉莫菲尔”,“姓名”:Enamul Haque,“错误代码”:“0”,“照片”:null}]}

  • 它可能以不同的方式完成。但我已经按照下面的方式完成了。请注意,如果您不需要任何参数来发送服务器,那么请删除参数选项。它可以使用post或get方法。您可以使用任何方式。我的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
                        }
                    }
    
    
                }
            }
       }
    
  • 如果使用类似表视图或集合视图等,则可以使用类似

  • 声明数组

    var arrRes=[String:AnyObject]

  • 将值赋给数组,如

    如果((responseData.result.value!=nil)){

  • 在taleView中,cellForRowAt indexPath只需使用

      let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:  indexPath) as! customCell
    cell.errorLabelName.text = arrRes[indexPath.row]["errorMessage"] as? String
    
  • 斯威夫特3 Swift 3中的阿拉莫菲尔示例

    导入UIKit 进口阿拉莫菲尔 导入快捷JSON

    类ViewController:UIViewController、UITableViewDelegate、UITableViewDataSource {

    }Swift 3 Swift 3中的阿拉莫菲尔示例

    导入UIKit 进口阿拉莫菲尔 导入快捷JSON

    类ViewController:UIViewController、UITableViewDelegate、UITableViewDataSource {


    }

    我尝试过使用“索引”或“价格”来转换,但出现错误
    无法将“\uu NSArrayM”(0x10c60ddb0)类型的值转换为“NSString”(0x10bc14c40)
    。啊,听起来你需要将转换与你的类型相匹配。我尝试过使用“索引”或“价格”来转换,但出现错误
    无法转换“\uu NSArrayM”(0x10c60ddb0)类型的值到“NSString”(0x10bc14c40)
    。啊,好吧,听起来你需要将你的演员阵容与你的类型相匹配。研究一下:我读了这篇文章,也许我很傻,但我找不到与我匹配的json模式,两天后我来到这里。这里有一个提示(实际上几乎是一个完整的解决方案):“项目”是一个包含数组的字典。此数组包含字典//结束,完成。我确实理解了很多,但仍然不足以找出有效的代码。我几乎记住了您链接的页面。许多示例和我正在处理的项目都使用NSDictionary,但我想使用[String:Any]研究一下:我读到了这篇文章,也许我很笨,但我找不到与我的json模式匹配的json模式,两天后我来到这里。这里有一个提示(实际上几乎是一个完整的解决方案):“items”是一个包含数组的字典。此数组包含字典//结束,完成。我确实理解了很多,但仍然不足以找出有效的代码。我几乎记住了您链接的页面。许多示例和我正在处理的项目都使用NSDictionary,但我想使用[String:Any]