huddie96 huddie96 - 1 month ago 20
JSON Question

Convert NSData from NSURLSession to JSON

I am aware that there are many similar SO questions that have a similar title to mine. I have checked them out and am still running into this problem.

I am trying to access an API that returns a string that should/could be formatted as JSON.

To retrieve this string as convert the string to JSON I'm using (unsuccessfully) this code:

NSError *error;

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {

NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"Response: %@",responseString);


NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];

id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

NSLog(@"%@",[json objectForKey:@"ID"]);


NSLog(@"Json: %@",json);

}];



[task resume];


The NSLog(@"Response:...) returns a string that when I enter it into this website: http://jsonviewer.stack.hu confirms that the string is valid JSON.

Both NSLog's that are supposed to return a JSON value come back null.

What iv'e tried:


  • NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
    options:NSJSONReadingMutableContainers
    error:&error];

  • NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
    options:NSJSONReadingMutableContainers
    error:&error];



I have also now tried:

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {


NSMutableDictionary *jsonObject;

NSError *err = nil;
@try
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}
@catch (NSException *exception)
{
NSLog( @"Exception caught %@",exception);
}

NSDictionary *info = jsonObject;

NSLog(@"Json: %@",info);

}];



[task resume];


What am I doing wrong here? How can I get a NSDictionary (JSON) result.

Answer

Try this:

  NSMutableDictionary *jsonObject;

    NSError *err = nil;
    @try
    {
        jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
    }
    @catch (NSException *exception)
    {
        NSLog( @"Exception caught %@",exception);
    }

    NSDictionary *info = jsonObject;