发布JSON时出现JSON错误 [英] JSON Error when posting JSON

查看:124
本文介绍了发布JSON时出现JSON错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将JSON数据发送到站点时,我总是收到错误消息.但是,当我检查站点时,我发现json中的所有数据均已发送并且是正确的.

I keep getting an error when trying to send JSON data to a site. But when I check the site, I see that all the data in json was sent and is correct.

我得到的错误是:

Error: 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.}

我的代码是:

let json = [
            "name": "john",
            "last name": "smith"
        ]

        do{

            let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)


            let url = NSURL(string: website)

            let request = NSMutableURLRequest(URL: url!)

            request.HTTPMethod = "POST"

            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = jsonData

            let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in

                if error != nil{
                    print("Error: \(error)")
                    return
                }

                do {
                    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                    print("Result: \(result)")

                } catch {
                    print("Error: \(error)")
                }
            }

            task.resume()

        } catch {
            print(error)
        }

当我允许片段时:

try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)

我遇到另一个错误:

Error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

我更改了:

try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)

try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments)

,我不再遇到错误.

推荐答案

在将数据成功发送到服务器后打印结果时发生错误.

The error happens when you print your result after the data is successfully sent to server.

NSJSONSerialization.JSONObjectWithData要求JSON以对象({})或数组([])开头.

NSJSONSerialization.JSONObjectWithData requires the JSON to start with an object ({}) or an array ([]).

尝试像这样添加.AllowFragments选项:

let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String:AnyObject]

如果它不起作用,则从服务器返回的数据是无效的JSON.您应该尝试打印responsestatusCode,看看是否有问题.

If it doesn't work, the data coming back from the server is invalid JSON. You should try printing the response's statusCode and see if there is a problem.

如果您控制服务器,则应查看发送回的内容.

If you control the server, you should look at what is sent back.

这篇关于发布JSON时出现JSON错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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