Подтвердить что ты не робот

Разбор JSON с использованием новых Swift 3 и Alamofire

Я использую Alamofire в качестве библиотеки HTTP, так как обновление до Swift 3, как вы разбираете JSON на примере ниже?

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

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

respone.result.value имеет любой объект и является очень новым и запутанным.

4b9b3361

Ответ 1

Как вы можете видеть в тестах Alamofire, вы должны отбрасывать response.result.value в [String:Any]:

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

Ответ 2

Обновлено для быстрого 3:

если ваш ответ похож на ниже,

[
    {
        "uId": 1156,
        "firstName": "Kunal",
        "lastName": "jadhav",
        "email": "[email protected]",
        "mobile": "7612345631",
        "subuserid": 4,
        "balance": 0
    }
]

**, если вы хотите разобрать вышеупомянутый ответ JSON, используемый ниже простых строк кода: **

    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

Если вы не хотите использовать SwiftyJson, сделайте это с помощью Alamofire 4.0:

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

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

Ключевым моментом является использование responseString вместо responseJSON.

Источник: https://github.com/Alamofire/Alamofire#response-string-handler