1
votes

I have created a file named Dict.json .Contents of the file are valid json containg

{"mydata":[{ "A":4, "B":14, "C":7 }, { "A":4, "B":12, "C":7 }, { "A":34, "B":154, "C":6 }, { "A":34, "B":162, "C":6 }]}

I want to create a NSDictonary from this file .I tried the following but it returns nil .

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Dict" ofType:@"json"]; NSMutableDictionary *newArr1=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

I am also checking that file is not nil;

NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
    NSLog("There is Data in File !!!!")  
}
2
Please read the docs for NSDictionary dictionaryWithContentsOfFile:.rmaddy
@rmaddy reading "NSDictionary dictionaryWithContentsOfFile:" thanksShekhu

2 Answers

0
votes

From the Documentation

+ (id)dictionaryWithContentsOfFile:(NSString *)path

Parameters

path

A full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary.

Return Value

A new dictionary that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.

As mentioned above you can only create the dictionary + (id)dictionaryWithContentsOfFile:(NSString *)path using plist file not from the .json.

3
votes

For loading the json data you will need NSJSONSerialization to fetch json data from file

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Dict" ofType:@"json"]; 
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *dic1 = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil] mutableCopy];

Your code only work on plist file, not on json file.