Parsing JSON using the new Swift 3 and Alamofire

梦想的初衷 提交于 2019-11-27 05:52:11

问题


I'm using Alamofire as HTTP library, since the update to Swift 3, how do you parse JSON based on the example below?

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    debugPrint(response)

    if let json = response.result.value {
        print("JSON: \(json)")
    }
}

respone.result.value is of Any object, and is very new and confusing.


回答1:


As you can see in Alamofire tests you should cast response.result.value to [String:Any]:

if let json = response.result.value as? [String: Any] {
  // ...
}



回答2:


Updated for swift 3 :

if your response is like below,

[
    {
        "uId": 1156,
        "firstName": "Kunal",
        "lastName": "jadhav",
        "email": "kunal@gmail.com",
        "mobile": "7612345631",
        "subuserid": 4,
        "balance": 0
    }
]

**if you want to parsing the above JSON response used below simple lines of code: **

    Alamofire.request(yourURLString, method: .get, encoding: JSONEncoding.default)
        .responseJSON { response in
            debugPrint(response)

            if let data = response.result.value{

                if  (data as? [[String : AnyObject]]) != nil{

                    if let dictionaryArray = data as? Array<Dictionary<String, AnyObject?>> {
                        if dictionaryArray.count > 0 {

                            for i in 0..<dictionaryArray.count{

                                let Object = dictionaryArray[i]
                                if let email = Object["email"] as? String{
                                    print("Email: \(email)")
                                }
                                if let uId = Object["uId"] as? Int{
                                    print("User Id: \(uId)")
                                }
                                // like that you can do for remaining...
                            }
                        }
                    }
                }
            }
            else {
                let error = (response.result.value  as? [[String : AnyObject]])
                print(error as Any)
            }
    }



回答3:


If you don't want to use SwiftyJson do this with Alamofire 4.0:

Alamofire.request("https://httpbin.org/get").responseString { response in
    debugPrint(response)

    if let json = response.result.value {
        print("JSON: \(json)")
    }
}

The key point being use responseString instead of responseJSON.

Source: https://github.com/Alamofire/Alamofire#response-string-handler



来源:https://stackoverflow.com/questions/39468516/parsing-json-using-the-new-swift-3-and-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!