发布JSON时出现JSON错误

时间:2016-08-21 00:48:14

标签: ios json swift post

尝试将JSON数据发送到网站时,我一直收到错误消息。但是当我检查网站时,我发现json中的所有数据都已发送并且是正确的。

我得到的错误是:

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)

我不再收到错误。

1 个答案:

答案 0 :(得分:4)

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

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

尝试添加.AllowFragments选项,如下所示:

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

如果它不起作用,从服务器返回的数据是无效的JSON。您应该尝试打印response的{​​{1}}并查看是否存在问题。

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