【发布时间】:2023-03-18 16:48:01
【问题描述】:
我正在使用来自 API 的响应并将其解析为 JSON。
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! [String: AnyObject]
let status = readableJSON["status"] as! String
if status == "success" {
if let profileInfo = readableJSON["profile_info"] {
let stb = UIStoryboard(name: "Main", bundle: nil)
let vcVerifyOTP = stb.instantiateViewController(withIdentifier: "verify_otp") as! VCVerifyOTP
vcVerifyOTP.sessionID = readableJSON["otp_session_id"] as! String
vcVerifyOTP.userID = readableJSON["customer_id"] as! String
vcVerifyOTP.first_name = profileInfo["firstname"] as! String
vcVerifyOTP.last_name = profileInfo["lastname"] as! String
vcVerifyOTP.email_id = profileInfo["email"] as! String
vcVerifyOTP.phone_number = profileInfo["mobile"] as! String
let scores = profileInfo["scores"] as! [String: AnyObject]
vcVerifyOTP.gmat = scores["gmat"] as! String
vcVerifyOTP.gre = scores["gre"] as! String
vcVerifyOTP.ielts = scores["ielts"] as! String
vcVerifyOTP.tofel = scores["tofel"] as! String
self.present(vcVerifyOTP, animated: true, completion: nil)
}
} else {
let alert = UIAlertController(title: "Error", message: "Login Unsuccessful.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
如果 'scores' JSONObject 包含任何数据,上面的代码可以正常工作,但如果它是空白应用程序崩溃。
如果“分数”包含数据(响应为) { “状态”:“成功”, “otp_session_id”:“某个值”, "customer_id":"somevalue", “profile_info”: { “名字”:“某个值”, “姓氏”:“某个值”, “电子邮件”:“一些价值”, "mobile":"somevalue", “分数”: { "gmat":"somevalue", "gre":"somevalue", "ielts":"somevalue", “托福”:“一些价值” } } }
如果“分数”不包含数据(响应为)(给出错误) { “状态”:“成功”, “otp_session_id”:“某个值”, "customer_id":"somevalue", “profile_info”: { “名字”:“某个值”, “姓氏”:“某个值”, “电子邮件”:“一些价值”, "mobile":"somevalue", “分数”:[0] } }
如果 'scores' 中有数据,则以 JSONObject 的形式出现,如果 'scores' 中没有数据,则以 JSONArray 的形式出现
现在,如果数组来了,它就会崩溃。我尝试了很多东西,但我无法捕捉到这个异常。我什至尝试检查 value 是 JSONObject 还是 JSONArray 但仍然没有成功。请帮忙。
【问题讨论】:
-
而不是自己处理所有这些。为什么不使用 ObjectMapper 或 SwiftyJson 之类的库?
-
所以首先你需要检查Score是否包含数据(键,值)如果是然后继续
-
是的,这会更容易,但问题是我的其他一些使用过的库存在兼容性问题,所以我试图避免使用新库。
-
@BhupatBheda 是的,但我不知道该怎么做......在同一个 Android 应用程序中我做了同样的事情,但我不能在 iOS 中做到这一点
-
你能告诉我Score Json对象的响应吗?