2013-02-15 119 views
0

我想弄清楚如何从应用程序本地访问json文件。目前我一直在远程使用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]; 

感谢

回答

1

你能更具体?你尝试访问哪个文件?你已经保存了吗?

1 /为您的主要问题:你可以创建一个dictionnary或阵列的文件路径

[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

+0

是我保存到应用程序。 – hanumanDev 2013-02-15 23:27:33

+0

你是怎么保存它的?哪条路?你应该能够很容易地做到“反向”:-) – Vinzius 2013-02-15 23:28:54

+0

我将它复制到项目中,就像将图像拖放到ios应用程序中一样 – hanumanDev 2013-02-15 23:32:51

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。

+0

我想你给了太多的信息。他不是在寻找如何做到这一点;-) – Vinzius 2013-02-15 23:35:29

+0

omg。我明白他是从您的Web服务o_o保存并加载json – 2013-02-15 23:39:06

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