Search code examples
jsonswiftnsdata

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


I'm having some problems with parsing data of an API to a Dictionary. I keep getting the error

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

But if I try to print it with this code:

if let s:NSString = String(data: data!, encoding: NSUTF8StringEncoding) {
     print(s)
}

it prints something like:

({"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":"...", ...}, ...]]})

To parse the data to a Dictionary I use:

let dict:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary

I'm stuck on this problem for several hours now and I think I've tried every possible combination of variable types and NSJSONReadingOptions

When I used .MutableContainers instead of .AllowFragments the error I got was:

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

So I added the option .AllowFragments.

I also checked if the string I was able to print is a valid JSON-object. I had to remove the () around it, but it was valid. So I asked the company which provides the data if they made a mistake, but they said everything works fine.

Can someone tell me what I'm doing wrong?


Solution

  • As the error says, "JSON text did not start with array or object" – that JSON is not valid, it's not your code at fault. You can validate this by pasting the JSON into an online JSON reader such as http://jsonlint.com – which will say the same thing as iOS.

    If the provider of the JSON won't provide it in another format, you'll have to clean it in your code by removing the first and last character if it comes in broken.