How to convert JSON serialized data to NSDictionary

IphoneObjective CIosJson

Iphone Problem Overview


I have used this method,

NSDictionary *jsonObject=[NSJSONSerialization 
       JSONObjectWithData:jsonData 
                  options:NSJSONReadingMutableLeaves 
                    error:nil];
NSLog(@"jsonObject is %@",jsonObject);

It's printing "jsonObject is null".
Is there any problem with "error:nil".
I am not using any url or connection methods.
I have a json file and I want to display it in a table.

Iphone Solutions


Solution 1 - Iphone

Please Try the following Code.

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:kNilOptions 
                                                       error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"];

NSLog(@"loans: %@", latestLoans);

Solution 2 - Iphone

Just in case anyone is here to see swift code:

> NSData to NSDictionary

let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary

> NSData to NSString

let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)

Solution 3 - Iphone

Check your json input, could it be that your root element is neither a dictionary nor an array? The documentation says you have to specify NSJSONReadingAllowFragments as the option in this case.

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
	NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

	NSData *jsonData = [@"{ \"key1\": \"value1\" }" dataUsingEncoding:NSUTF8StringEncoding];
	NSDictionary *jsonObject=[NSJSONSerialization 
	       JSONObjectWithData:jsonData 
	                  options:NSJSONReadingMutableLeaves 
	                    error:nil];
	NSLog(@"jsonObject is %@",jsonObject);

	[p release];
}

Output:

2012-09-26 16:06:51.610 Untitled[19164:707] jsonObject is {
    key1 = value1;
}

Solution 4 - Iphone

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

This is just a more succinct version of the top post.

Solution 5 - Iphone

> let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajeshView Question on Stackoverflow
Solution 1 - Iphoneamit soniView Answer on Stackoverflow
Solution 2 - IphoneiAhmedView Answer on Stackoverflow
Solution 3 - Iphoneuser111823View Answer on Stackoverflow
Solution 4 - IphoneLuis BView Answer on Stackoverflow
Solution 5 - IphoneSoftlabsindiaView Answer on Stackoverflow