【发布时间】:2019-02-25 06:35:50
【问题描述】:
我正在开发一个 iOS 应用程序,它使用 API 来获取用户信息。这是我从服务器返回的响应,它是一个 JSON 对象:
{
"status": {
"code": 200,
"message": "OK",
"error": 0,
"error_messages": []
},
"data": {
"id": 1111,
"name": "xxxxxxxx",
"triple_name": "xxxxxxxx",
"english_name": "xxxxxxxx",
"email": "xxxxxxxx",
"telephone": "xxxxxxxx",
"username": "xxxxxxxx",
"id_type": "xxxxxxxx",
"id_number": "xxxxxxxx",
"id_expiry_date": null,
"id_photo": null,
"gender": "xxxxxxxx",
"date_of_birth": "xxxxxxxx",
"h_date_of_birth": null,
"nationality_id": 0,
"country_id": 0,
"city_id": 0,
"degree_id": null,
"personal_photo": null,
"is_government_employee": 0,
"iban": null,
"bank_id": null,
"access_token": "xxxxxxxx",
"country_name": "xxxxxxxx",
"city_name": "xxxxxxxx"
}
}
但是,我在这行代码中遇到错误:
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
错误是:
字符 0 周围的值无效
。我使用了 JSON 验证器,它说 JSON 是有效的。但是,我不断收到此错误
【问题讨论】:
-
是的,json 是有效的我认为你已经为 AlamOFire 创建了任何包装类,并且在那个键“错误”中传递值有一些问题,请检查你传递数据的那部分“状态”数据
-
尝试将
options: .allowFragments更改为options: [] -
错误提示 JSON not 有效。在 JSONSerialization 行之前打印字符串:
print(String(data:data!, encoding:.utf8)!)。我猜是HTML。并且不要在 Swift 中使用NSDictionary,如果预期类型是字典,allowFragments将毫无意义。 -
我在这里运行了你的代码,repl.it/repls/LumberingCheerfulIntercept,它可以工作,也许你在搞砸别的东西。
-
@vadian 我添加了你建议的语句,我得到了这个回复:
400 Bad Request Bad Request
您的浏览器发送了此服务器无法理解的请求。
Apache/2.4.27 (Ubuntu) Server at platform.xxxxx.sa 端口 80 这是否意味着我的响应是 HTML?事件虽然当我用邮递员尝试它时我得到 JSON 对象
标签: ios json swift api jsonparser