在iOS Swift中使用alamofire检索json

问题描述 投票:-1回答:1
[
    {
        "id": 1,
        "Name": "Vignesh"
    },
    {
        "id": 2,
        "Name": "Suresh"
    }
]

 AlamofireHC.requestPOST("Url", params: param as [String : AnyObject], headers: header, success: { (JSON) in

                  let  result = JSON.dictionaryObject
                  let json = result! as NSDictionary
                var arrBookingList = json.value(forKey: "Name") as! Array<Any>

}

但是它显示了我的错误..帮助我完成这是我的第一个项目

ios swift alamofire swifty-json
1个回答
0
投票

您的JSON以数组开头,因此您需要首先对数组进行迭代,然后再使用字典数组中要使用的键

例如

 AlamofireHC.requestPOST("Url", params: param as [String : Any], headers: header, success: { (json) in
               // initally check your json is array or not after that check your contains object or not
                    guard let dataArray =  json.array, !dataArray.isEmpty else { return }
            // extract the dictionary from array
             for getDict in dataArray  {
            // finally print your name string from dict
             print("name == \(getDict["Name"].stringValue)")
            }    
    }

或快速方式

 AlamofireHC.requestPOST("Url", params: param as [String : Any], headers: header, success: { (json) in
               // initally check your json is array or not after that check your contains object or not
                    guard let dataArray =  json.array, !dataArray.isEmpty else { return }
                dataArray.forEach {  print("name == \($0["Name"].stringValue)") }

    }
© www.soinside.com 2019 - 2024. All rights reserved.