0

am very to new to swift and i am trying to parse JSON form a url. I am receiving the object but it is being returned as a bunch of numbers. How do I decode these numbers into the actual object.

let requestURL: NSURL =  NSURL(string: "http://api.themoviedb.org/3/search/movie?api_key=06f4ca4cd5f26636e0ac8eebce5b8773&query=fight+club&callback=testing&_=1456113299076")!

let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in

let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode

if (statusCode == 200) {

    if (statusCode == 200) {

        do{
            print(data)
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)



        }catch {
            print("Error with Json: \(error)")

        }

    }

}
}
task.resume()

1 Answer 1

1

An error occurs with error message

Error Domain=NSCocoaErrorDomain Code=3840 "Something looked like a 'true' but wasn't around character 0."

That means the string is not valid JSON (wrongly formatted) right from the beginning.

Solution:

For some incomprehensible reason the JSON string is wrapped in a testing(...) block.

You need to trim the data from byte 9 (index 8) until second to last.

do{
    let trimmedData = data!.subdataWithRange(NSRange(location:8, length: data!.length - 9))
    let json = try NSJSONSerialization.JSONObjectWithData(trimmedData, options: .AllowFragments)
    print(json)
  }
  ...

PS: In the completion block it's highly recommended to check if the error is not nil before getting the statusCode

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.