Search code examples
iosobjective-cjsonafnetworkingnsurlsession

Converting NSData to NSDictionary


I am trying to fetch data from an url https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json

I am getting nil while converting nsdata to nsdictionary.

I used the following code. and I am able to log the data as well. but as soon as I convert it into dictionary it is showing nil.What am I missing here?

I tried nsurlsession and afnetworking as well. getting the same error.

NSError *error;
NSString *url_string = [NSString stringWithFormat: DATA_URL];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"json: %@", json);

Solution

  • You have to convert NSDatainto UTF8 before parsing it using NSJSONSerialization.

    NSError* error = nil;
    
    NSString *strISOLatin = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
    NSData *dataUTF8 = [strISOLatin dataUsingEncoding:NSUTF8StringEncoding];
    
    id dict = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:0 error:&error];
    if (dict != nil) {
        NSLog(@"Dict: %@", dict);
    } else {
        NSLog(@"Error: %@", error);
    }