为Dictionary分配长JSON响应会产生Thread错误

时间:2018-03-14 11:35:12

标签: ios json swift dictionary

当尝试为字典分配长JSON响应时,我得到

  

  

主题1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

分配简短回复可以正常工作。这是我的代码

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
                    }
            }
        }
    }

3 个答案:

答案 0 :(得分:3)

首先,您要转换为可选字典,因此它应该是条件绑定,即:

if let unwrappedJson = json as? ....

其次,你应该转向[String : Any],即:

    if let unwrappedJson = json as? [String : Any]

答案 1 :(得分:1)

您必须将响应序列化为json,然后才能将其用作字典。

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

然后打印这个json

或者

使用此链接,这是从apple到代码的最新更新,并根据您的班级或模型编码json响应。

Automatic JSON serialization and deserialization of objects in Swift

答案 2 :(得分:1)

可能有帮助..

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)
        }
    }