如何从应用程序中本地访问json文件

han*_*Dev 0 iphone json objective-c initwithcontentsoffile ios

我试图找出如何在应用程序内本地访问json文件.目前我一直在从这样的服务器远程使用json文件:

jsonStringCategory = @"http://****categories?country=us";
    }

    // Download the JSON file
    NSString *jsonString = [NSString
                            stringWithContentsOfURL:[NSURL URLWithString:jsonStringCategory]
                            encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
                            error:nil];

    NSLog(@"jsonStringCategory is %@", jsonStringCategory);

    NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];

    // Create parser 
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *results = [parser objectWithString:jsonString error:nil];

    itemsTMP = [results objectForKey:@"results"];

    self.arForTable = [itemsTMP copy];

    [self.tableView reloadData];
Run Code Online (Sandbox Code Playgroud)

我试过这个:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"categoriesus" ofType:@"json"];


    jsonStringCategory = [[NSString alloc] initWithContentsOfFile:filePath];
Run Code Online (Sandbox Code Playgroud)

谢谢

小智 8

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
Run Code Online (Sandbox Code Playgroud)