JSON序列化时发生错误ErrorDomain代码= 3840 [英] error while doing JSON Serialization ErrorDomain Code=3840

查看:122
本文介绍了JSON序列化时发生错误ErrorDomain代码= 3840的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除表格视图中的帖子,但在此行中进行JSON序列化时出现错误

I am trying to delete a post in a table view, but I get an error while doing JSON serialization, in this line

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

如果我通过浏览器访问url,则数据已成功删除数据库中的数据,如果从浏览器访问了数据,它也会像这样返回json响应

if i access the url through the browser, the data is successfully deleted in the database, and if it is accessed from the browser, it also gives the json response back like this

{消息":成功删除",结果":1,状态":图像已被删除 从驱动器中删除"}

{"message":"successfully deleted","result":1,"status":"Image has been deleted from drive"}

但是我遇到一个错误,说json文本不是以数组或对象开头(代码= 3840),但是正如您在上面看到的那样,它是一个json字典

but i got an error that says the json text did not start with array or object (code =3840), but as you can see above, it is a json dictionary

Error Domain = NSCocoaErrorDomain代码= 3840"JSON文本不是以数组或对象开头,并且未设置允许片段的选项. UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且未设置允许片段设置的选项.}

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

这是我使用的完整代码.这里出了什么问题?谢谢

here is the full code i use. what went wrong in here? Thanks

func deletePost(_ indexPath: IndexPath) {

    let tweet = tweetsArray[indexPath.row]
    let uuid = tweet["uuid"] as! String
    let imagePath = tweet["imagePath"] as! String

    let url = URL(string: "http://localhost/Twitter/post.php")
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    let body = "uuid=\(uuid)&path=\(imagePath)"
    request.httpBody = body.data(using: String.Encoding.utf8)

    let session = URLSession.shared
    let task = session.dataTask(with: request) { (data, response, error) in

        if error == nil {

            do {

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

                guard let parsedJSON = json else {
                    print("error while parsing JSON")
                    return
                }

                let jsonMessage = parsedJSON["message"]
                if jsonMessage != nil {
                    // hilangkan data di array
                    self.tweetsArray.remove(at: indexPath.row)
                    self.imagesArray.remove(at: indexPath.row)

                    // hilangkan rownya pada table view
                    self.tableView.deleteRows(at: [indexPath], with: .automatic)
                    self.tableView.reloadData()
                }
            }
            catch {

                // get main queue to communicate back to user
                DispatchQueue.main.async(execute: {
                    let message = "\(error)"
                    self.showAlert(alertTitle: "sorry", alertMessage: message, actionTitle: "OK")
                })
                return
            }
        }
        else {

            // get main queue to communicate back to user
            DispatchQueue.main.async(execute: {
                let message = "\(error!.localizedDescription)"
                self.showAlert(alertTitle: "sorry", alertMessage: message, actionTitle: "OK")
            })
            return
        }
    }
    task.resume()
}

推荐答案

您可以尝试打印出服务器响应.请像这样在您的catch块中更改代码.并确定服务器端是否存在错误.

You can try to Print out your server response. Please change the code in your catch block like. and identifying an error in server side or not.

您的服务器数据是正确的json格式,然后打印出您的服务器数据并检查服务器数据是否有效.

Your server data is proper json formate then print out your server data and check a server data is valid or not.

URLSession.shared.dataTask(with: url) { (data, response, error) in

        if let jsonData = data {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as! [String: AnyObject]
                if let area = parsedData["AREA"] as? [[String: AnyObject]] {
                    for a in area {
                        print(a["area_name"])
                        print(a["price"])
                    }
                }
            }
            catch let err{
                print("\n\n===========Error===========")
                print("Error Code: \(error!._code)")
                print("Error Messsage: \(error!.localizedDescription)")
                if let data = data, let str = String(data: data, encoding: String.Encoding.utf8){
                    print("Server Error: " + str)
                }
                debugPrint(error)
                print("===========================\n\n")

                debugPrint(err)
            }
        }
        else {
            debugPrint(error as Any)
        }

    }.resume()

这篇关于JSON序列化时发生错误ErrorDomain代码= 3840的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆