提问人:Johnd 提问时间:7/17/2023 最后编辑:Johnd 更新时间:7/17/2023 访问量:130
错误(Xcode、Swift):由于错误,无法序列化 JSON:无法读取数据,因为它的格式不正确
Error (Xcode, Swift): JSON could not be serialized because of error: The data couldn't be read because it isn't in the correct format
问:
几年前我做了一个应用程序,现在正在尝试更新它。当我运行 Alamofire 请求时,我收到一条消息,“JSON 无法序列化,因为错误:无法读取数据,因为它的格式不正确。澄清一下,这不会使我的应用程序崩溃。相反,它没有在应该提取任何数据时提取任何数据,并返回上述消息。
我已经更新了我的 cocoapods,但我有一段时间没有编码了,所以我不太确定问题出在哪里。
let brandName = restaurantField.text!
let foodName = itemNameField.text!
// let url = "https://api.nutritionix.com/v2/search/"
let url = "https://trackapi.nutritionix.com/v2/search/"
let params = [
"appId":"66ebb194",
"appKey":"2e43991be685bcd5836574dda12e4625",
"queries":[
"food_name":foodName,
"brand_name":brandName
],
"fields":["item_name","brand_name","nf_total_carbohydrate","nf_serving_size_qty","nf_serving_size_unit"],
"filters":[
"item_type":1
]
] as [String : Any]
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
switch (response.result) {
case .success:
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
//old syntax - swift 3
// if let json = response.result.value {
// print("JSON: \(json)") // serialized json response
//
// }
switch response.result {
case let .success(value):
print(value)
case let .failure(error):
print(error)
print("\n\n===========Error===========")
print("Error Code: \(error._code)")
print("Error Messsage: \(error.localizedDescription)")
if let data = response.data, let str = String(data: data, encoding: String.Encoding.utf8){
print("Server Error: " + str)
}
debugPrint(error as Any)
print("===========================\n\n")
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
let json = try! JSON(data: response.data!)
if let objects = json["hits"].array{
for object in objects{
self.items.append(Item(json: object.dictionaryValue))
print(self.items)
print(self.items[0].carbs)
self.tableView.reloadData()
self.itemNameField.text = ""
self.restaurantField.endEditing(true)
self.itemNameField.endEditing(true)
}
}
if self.items.count == 0{
let alert = UIAlertController(title: "No results from search", message: nil, preferredStyle: UIAlertController.Style.alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}
break
case .failure(let error):
print("\n\n===========Error===========")
print("Error Code: \(error._code)")
print("Error Messsage: \(error.localizedDescription)")
if let data = response.data, let str = String(data: data, encoding: String.Encoding.utf8){
print("Server Error: " + str)
}
debugPrint(error as Any)
print("===========================\n\n")
if error._code == NSURLErrorTimedOut {
}
希望这足以提供解决方案的信息,但如果还有其他我应该提供的东西,请告诉我。
以下是错误描述的打印输出...
Error Messsage: JSON could not be serialized because of error:
The data couldn’t be read because it isn’t in the correct format.
Server Error: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /v2/search/</pre>
</body>
</html>
Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0}))
答: 暂无答案
评论
print(error)
POST
GET
method: .post
method: .get