0

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

谢谢

4

3 回答 3

8
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
于 2013-02-15T23:39:40.057 回答
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

于 2013-02-15T23:25:12.427 回答
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 的名称。

于 2013-02-15T23:28:28.487 回答