How do I access a nested JSON value using Alamofire and SwiftyJSON?

前端 未结 2 794
误落风尘
误落风尘 2021-01-15 06:25

I am trying to access nested JSON results using swiftyJSON and Alamofire. My print value is nill and I believe I am not doing this correctly. What should my parameters be? I

2条回答
  •  孤街浪徒
    2021-01-15 06:33

    If the syntax of the json isn't correct, since it is fully printed anyway you should notice what's wrong.

    func getAPI() {
    Alamofire.request(.GET, "http://quotes.rest/qod.json", parameters: ["contents": "quotes"])
        // JSON response
            .responseJSON { response in switch response.result {
            case .Failure(let error):
                // got an error in getting the data, need to handle it
                print("error calling GET, json response type :")
                // print alamofire error code
                let statusCode = error.code
                print("error code json : \(statusCode)")
                // print json response from server
                if let data = response.data {
                    print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
                }
                // print http status code plus error string
                print(NSHTTPURLResponse.localizedStringForStatusCode(statusCode))
                if let httpResponse : NSHTTPURLResponse = response.response {
                    print("HTTP Response statusCode: \(httpResponse.statusCode)")
                }
            case .Success( _):
                let statusCode = (response.response?.statusCode)!
                print("status code json : \(statusCode)")
                print("there is a response json")
                //print(value)
                // parse the result as JSON, since that's what the API provides and save datas as new user in coreData
                guard let data = response.data else {
                    print("Error parsing response data")
                    return
                }
                let json = JSON(data: data)
                // access first element of the array
                if let postContent = json["contents"]["quotes"][0]["quote"].string{
                 // deal with json
                }
           }
    }
    

提交回复
热议问题