错误(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

提问人:Johnd 提问时间:7/17/2023 最后编辑:Johnd 更新时间:7/17/2023 访问量:130

问:

几年前我做了一个应用程序,现在正在尝试更新它。当我运行 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}))
json swift 阿拉莫火

评论

0赞 Rob Napier 7/17/2023
检查传入的 JSON。正如错误所示,它可能无效。或者,如果错误来自服务器,请验证要发送的 JSON 是否正确。看起来您已经更换了服务器。他们可能更改了他们的 API。
0赞 lorem ipsum 7/17/2023
相反,使用你得到一个更好的错误,它会告诉你到底出了什么问题print(error)
0赞 Johnd 7/17/2023
我编辑了问题以包含打印(错误)输出
0赞 Larme 7/17/2023
你得到一个HTML/XML错误,这是非常明确的,它说你不能只在那里做一个。 -> ?POSTGETmethod: .postmethod: .get
1赞 Joakim Danielson 7/17/2023
您应该了解 HTTP GET 和 POST 之间的区别,但更重要的是,由于您收到一条错误消息,说您不能使用 POST,那么显然您正在使用的 API 已更改,因此您需要查看它的文档以了解如何调整 http 调用。

答: 暂无答案