Search code examples
jsonswiftalamofire

Parsing issue in Swift 3.0


I am using the Swift 3.0 and Almofire. In below data how I can use url key's value from this response data.

Printing description of parsedData:

▿ 3 elements
  ▿ 0 : 2 elements
    - .0 : "status_txt"
    - .1 : OK
  ▿ 1 : 2 elements
    - .0 : "status_code"
    - .1 : 200
  ▿ 2 : 2 elements
    - .0 : "data"
    ▿ .1 : 5 elements
      ▿ 0 : 2 elements
        - .0 : long_url
        - .1 : http://google.com
      ▿ 1 : 2 elements
        - .0 : hash
        - .1 : 2lOLF92
      ▿ 2 : 2 elements
        - .0 : global_hash
        - .1 : 2lOL6fc
      ▿ 3 : 2 elements
        - .0 : url
        - .1 : http://google.com
      ▿ 4 : 2 elements
        - .0 : new_hash
        - .1 : 1

Alamofire.request("http://my url").responseJSON { (responseObject) -> Void in
    switch responseObject.result {
    case .success(let data):
        let bytes = try! JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)
        var jsonObj = try! JSONSerialization.jsonObject(with: bytes, options: .mutableLeaves)
        print("parsedData\(jsonObj)")

    case .failure(let error):
        print("Request failed with error: \(error)")
    }
}

Solution

  • You have used Response JSON Handler not the Response Data Handler, so in this case with case .success(let data) you will get Serialized JSON response so need to use again JSONSerialization with it, Simply convert it to array and you can go for it.

    Alamofire.request("http://my url").responseJSON { (responseObject) -> Void in
        switch responseObject.result {
        case .success(let value): //batter to use value
            if let dictionary = value as? [String:Any], 
               let dataDic = dictionary["data"] as? [String:Any],
               let url = dataDic["url"] as? String {
                   print(url)
            }
    
    
        case .failure(let error):
            print("Request failed with error: \(error)")
        }
    }