0

When trying to assign a long JSON response to a Dictionary, I get either

nil

or

Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Assigning a short response works fine. Here is my code

func getUserInfo() {
        let access_token : String = accessToken_json_response["access_token"] ?? "empty"
        if access_token != "empty" {
            Alamofire.request("https://api.github.com/user?access_token=\(access_token)").responseJSON { response in
                    if let json = response.result.value {
                        print(json) //The JSON prints, but takes more than a second to do so.   
                        self.getUser_json_response = json as? Dictionary<String, String> //This produces the thread error when the response is long.
                        print(self.getUser_json_response) //This either prints nil, or a thread error produces in the previous instruction
                    }
            }
        }
    }
Amine
  • 1,396
  • 4
  • 15
  • 32

3 Answers3

3

First of all you are casting to an optional dictionary so it should be conditional binding i.e:

if let unwrappedJson = json as? ....

Second, you should cast to [String : Any] i.e:

    if let unwrappedJson = json as? [String : Any]
OhadM
  • 4,687
  • 1
  • 47
  • 57
  • This works, but why do I have to cast to [String: Any] and not [String:String]? (I've already done this previously with another json and it worked with the [String:String] cast) – Amine Mar 14 '18 at 11:44
  • I don't know the content of your data but to be on the safe side you should cast to [String : Any] and only then conditional bind the rest because a key could have a value of an array or another dictionary in it and String won't cut it... – OhadM Mar 14 '18 at 11:48
1

You have to serialise the response into json and then you can use it as dictionary.

eg: let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]

then print this json

Or

Use this link, this is latest update from apple to code and encode json response according to your class or model.

Automatic JSON serialization and deserialization of objects in Swift

Mridul Gupta
  • 599
  • 5
  • 18
1

may this help..

Alamofire.request(UrlStr, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil)
            .validate()
            .responseJSON { response in

                switch response.result {
                case .success:
                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")

                        let jsonResponse = (JSON as? [String:Any]) ?? [String:Any]()

                       print("jsonResponse: \(jsonResponse)")


                    }
                case .failure(let error):

                    print(error.localizedDescription)
        }
    }
Uday Babariya
  • 1,031
  • 1
  • 13
  • 31