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

时间:2013-02-15 23:12:28

标签: iphone ios objective-c json initwithcontentsoffile

我正试图弄清楚如何在应用程序内本地访问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];

我试过了:

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


    jsonStringCategory = [[NSString alloc] initWithContentsOfFile:filePath];

感谢

3 个答案:

答案 0 :(得分:8)

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];

答案 1 :(得分:1)

你可以更具体一点吗?您尝试访问哪个文件?你已经保存了吗?

1 /对于您的主要问题:您可以创建带有文件路径的字典或数组

[NSDictionary dictionaryWithContentsOfFile:<#(NSString *)#>]
[NSArray arrayWithContentsOfFile:<#(NSString *)#>]

2 /但是,您可以在编写时从文件中读取“字符串”内容,然后最终解析它。为此你需要(例如)这样的路径(对于“目录”目录,可以是“缓存”目录)

NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToFile = [ [ [ [ array objectAtIndex:0 ] stringByAppendingPathComponent:@"nameOfTheFile" ] stringByAppendingString:@".ext" ] retain ];

然后在我的1 /示例中使用“pathToFile”。

3 /为了您的互联网访问,我建议您检查AFNetworking。做异步下载更好;-)(你的同步)

https://github.com/AFNetworking/AFNetworking

答案 2 :(得分:1)

我喜欢使用CoreData。请按照以下步骤操作:

1-)首先创建一个模型,并添加名称为jsonvalue的属性String类型。

2-)创建此函数以保存您的json文件:

    -(void)saveJson:(NSString*)d
    {

       NSString * data = [d retain];

       NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"NameObjectModel" inManagedObjectContext:context]];

    NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    [request release];
    // error handling code
    if(error){

    }
    else{
        Session* favoritsGrabbed = [results objectAtIndex:0];
        favoritsGrabbed.jsonvalue = data;
    }

    if(![context save:&error]){
        NSLog(@"data saved.");
    }
}

3-)创建一个加载json的函数:

-(void)loadJSONFromFile
{

    //Recover data from core data.

    // Define our table/entity to use
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"NameObjectModel" inManagedObjectContext:context];

    // Setup the fetch request
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];

    // Define how we will sort the records - atributo que sera recuperado
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"jsonvalue" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

    [request setSortDescriptors:sortDescriptors];
    [sortDescriptor release];

    // Fetch the records and handle an error
    NSError *error;
    NSMutableArray *mutableFetchResults = [[NSMutableArray alloc]initWithArray:[context executeFetchRequest:request error:&error]];

    if (!mutableFetchResults) {
        // Handle the error.
        // This is a serious error and should advise the user to restart the application
    }

    if(mutableFetchResults.count == 0)
    {
        NSLog(@"the archive is null");
    }

    else if(mutableFetchResults.count > 0)
    {
        NameObjectModel *entity = [mutableFetchResults objectAtIndex:0];
        //NSLog(@"%@",[[entity jsonvalue] JSONValue]);
        NSDictionary * aux = [[entity jsonvalue] JSONValue];

        if([entity jsonvalue]== nil)
        {
            NSLog(@"json is nil");
            NSLog(@"the archive exists but json is nil");
        }

        else {
            // set current json data cache
            [self setJsonCache:aux]; // add to recovery list
        }

    }
    [mutableFetchResults release];
    [request release];
}

不要忘记:NameObjectModel = NSManagedObject的名称。