无法将 API-Response 转换为 JSON 但可以将其打印为字符串

Unable to convert API-Response to JSON but it works to print it as a string

我在将 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-object。我不得不删除它周围的 (),但它是有效的。所以我问了提供数据的公司,如果他们出错了,他们说一切正常。

谁能告诉我哪里做错了?

如错误所述,"JSON text did not start with array or object" – JSON 无效,这不是您的代码错误。您可以通过将 JSON 粘贴到在线 JSON reader 中来验证这一点,例如 http://jsonlint.com – 这与 iOS.[=11= 表示相同的内容]

如果 JSON 的提供者不会以另一种格式提供它,您必须在代码中清理它,方法是删除损坏的第一个和最后一个字符。