Sekhar
Sekhar

Reputation: 339

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);

Upvotes: 8

Views: 9598

Answers (2)

cptdanko
cptdanko

Reputation: 842

If you are looking for the Swift equivalent of Jayesh Thanki's Objective-C code, here it is,

let str = String(data: d, encoding: .isoLatin1)
let data8 = str?.data(using: .utf8)
let result = try JSONSerialization.jsonObject(with: data8!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

Upvotes: -2

Jayesh Thanki
Jayesh Thanki

Reputation: 2077

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);
}

Upvotes: 12

Related Questions