我在将API的数据解析为字典时遇到了一些问题。我一直在犯错误
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
但如果我试图用这段代码打印出来:
if let s:NSString = String(data: data!, encoding: NSUTF8StringEncoding) {
print(s)
}
它打印的内容如下:
({"user":{"id":4008257,"firstname":"FIRSTNAME","lastname":"LASTNAME","role":"ROLE"},"timetable":[[{"date":"2015-11-09","lessons":[{"id":42563,"title":"SUBJECT","location":"ROOM","acronym":"TEACHER","class":"CLASS","start":"2015-11-09T08:35:00+01:00","end":"2015-11-09T09:15:00+01:00","duration":2400,"eventType":"lesson"}, {"id":...}, ...]}, {"date":"...", ...}, ...]]})
要将数据解析为字典,我使用:
let dict:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
我在这个问题上被困了好几个小时了,我想我已经尝试过各种变量类型和NSJSONReadingOptions的组合
当我使用.MutableContainers而不是.AllowFragments时,我得到的错误是:
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.}
因此,我添加了选项.AllowFragments。
我还检查了我能够打印的字符串是否是一个有效的JSON对象。我不得不删除它周围的(),但它是有效的。所以我问提供数据的公司,如果他们犯了错误,但他们说一切正常。
有人能告诉我我做错了什么吗?
发布于 2015-12-13 03:55:57
正如错误描述的那样,"JSON文本没有以数组或对象开头“-- JSON无效,这不是您的错误代码。您可以通过将JSON粘贴到在线JSON阅读器(如http://jsonlint.com )中验证这一点--这将与iOS一样。
如果JSON的提供者不会以另一种格式提供它,那么如果第一个和最后一个字符出现故障,就必须在代码中清除它。
https://stackoverflow.com/questions/34250777
复制