发布JSON时出现JSON错误

编程入门 行业动态 更新时间:2024-10-15 18:23:11
本文介绍了发布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.您应该尝试打印response的statusCode,看看是否有问题.

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

本文发布于:2023-11-26 22:02:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635375.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!