如何在 NSDictionary 中访问本地 JSON 文件响应以在 UITableView 中显示?

Posted

技术标签:

【中文标题】如何在 NSDictionary 中访问本地 JSON 文件响应以在 UITableView 中显示?【英文标题】:How to Access local JSON file response in NSDictionary for showing in UITableView? 【发布时间】:2016-04-01 04:58:16 【问题描述】:

基本上我从服务器端得到响应,然后将其保存在本地文件中。实际上我从服务器端获取响应,然后保存到文档目录中,现在尝试获取但它仅在 NSString 中,我无法获取在 NSDictionary....这里是下面的代码

- (IBAction)loginButtonPressed:(id)sender

    NSString *URLString = @"http://localhost/rest/login";

    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    NSDictionary *params = @@"username": userNameTxtField.text, @"password": pwdTextField.text;
    NSLog(@"Parameters:\n%@",params);

    [manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask *operation, id responseObject)
    

        NSLog(@"Successfully Login ....: %@", responseObject);

        NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        path = [NSString stringWithFormat:@"%@/sample.json", documents];

        NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
        [stream open];

        NSError  *writeError = nil;

        NSInteger bytesWritten = [NSJSONSerialization writeJSONObject:responseObject toStream:stream options:NSJSONWritingPrettyPrinted error:&writeError];

        if ((bytesWritten = 0))
        
            NSLog(@"Error writing JSON Data");
        
        else
            NSLog(@"Sucessfuly saved data...");
        
          [stream close];

        NSLog(@"path is :%@",path);

     failure:^(NSURLSessionDataTask *operation, NSError *error)

    
        NSLog(@"Error: %@", error);
    ];


- (IBAction)fetch:(id)sender

    NSError *deserializingError;
    NSData *data=[NSData dataWithContentsOfFile:path];
    NSString *jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&deserializingError];

    NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data  options:kNilOptions error:nil];

    NSLog(@"vaues are:%@",dict);

【问题讨论】:

从响应中获取数据并将其保存为数组并加载到表中。 而不是将其存储在本地文件中。您可以将其保存为 Core Data、Sqlite 和 NSUserDefault。因此,您可以从应用程序的任何位置获取。 感谢您的回复,但我必须维护太多文件,所以我应该维护文件格式,实际上我得到了 NSData 中的内容,但它是字节格式的,所以我想将它们作为密钥获取并值格式。 【参考方案1】:

您的响应对象应该是一种 NSDictionary。因此,您可以使用它的 writeToFileAtPath 方法将其保存到您的文档目录中。

在重新创建字典时,可以使用 NSDictionary 的 alloc 和 initWithContentsOfFile 方法直接创建一个 NSDictionary 实例。

如果您进行一点 Google 搜索,有大量关于如何做到这一点的帖子!

【讨论】:

>您的响应对象应该是 NSDictionary 类型。真的吗? 嗨,El Tomato。此人指定了以下 LOC。这意味着如果我是对的,该库将解析 json 并将其转换为基础对象。manager.responseSerializer = [AFJSONResponseSerializer serializer]; 嗨 EI 番茄是的.. 我的 resposeObject 是一个 nsdictionary 格式,包含键和值 你有没有尝试我的建议 Govind? 嗨 Ruchira .. 无论我在下面的代码中做什么都是正确的?NSInteger bytesWritten = [NSJSONSerialization writeJSONObject:responseObject toStream:stream options:NSJSONWritingPrettyPrinted error:&writeError]; if ((bytesWritten = 0)) NSLog(@"写入 JSON 数据时出错"); else NSLog(@"成功保存数据..."); [流关闭];【参考方案2】:

试试这个!!它工作正常。

            NSMutableDictionary *testStore = [[NSMutableDictionary alloc] init];
            [testStore setObject:@"vignesh" forKey:@"username"];
            [testStore setObject:@"password" forKey:@"password"];

            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:testStore // Here you can pass array or dictionary
                                                               options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                                 error:&error];
            NSString *jsonString;
            if (jsonData) 
                jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                //This is your JSON String
                //NSUTF8StringEncoding encodes special characters using an escaping scheme
             else 
                NSLog(@"Got an error: %@", error);
                jsonString = @"";
            


            [self writeStringToFile:jsonString];

            NSLog(@"Your JSON String is %@", [self readStringFromFile]);

        - (void)writeStringToFile:(NSString*)aString 

            // Build the path, and create if needed.
            NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString* fileName = @"bookmark.json";
            NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];

            if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) 
                [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
            

            // Write to file
            [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
        

        - (NSString*)readStringFromFile 

            // Build the path...
            NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString* fileName = @"bookmark.json";
            NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];

            // read from file
            return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
        

【讨论】:

这是代码:-(void)FetchData NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:FilePath]; NSLog(@"值为 %@",dictionary); NameArray=[字典 valueForKey:@"first_name"]; NSMutableArray *LastNameArray=[字典 valueForKey:@"last_name"]; NSLog(@"学生的名字是:%@",NameArray); NSLog(@"学生的姓是:%@",LastNameArray); 【参考方案3】:
static const char *dbPath = nil;
static sqlite3_stmt *ermsg = nil;
static sqlite3 *studs =nil;
static DatabaseOperation *_sharedInstances = nil;

@implementation DatabaseOperation
@synthesize databasePath;

+(DatabaseOperation*)sharedInstances
    if(!_sharedInstances)
        _sharedInstances =[[super allocWithZone:nil]init];
    
    return _sharedInstances;

+(id)allocWithZone:(struct _NSZone *)zone
    return  [self sharedInstances];

-(id)init
    NSLog(@"Only first time Instances using Singleton:");
    self =[super init];
    if(self)
        [self CreateDbpath];
    
    return self;


-(BOOL)CreateDbpath

    NSArray *dbpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docdir=[[NSString alloc]initWithString:[dbpaths objectAtIndex:0]];

    self.databasePath =[[NSString alloc]initWithString:[docdir stringByAppendingPathComponent:@"Mindset.sqlite"]];

    NSFileManager *flg  = [NSFileManager defaultManager];

    BOOL isSuccess = false;

    if([flg fileExistsAtPath:databasePath]==NO)

        char  *ermsgss = nil;

        char const *dbpathss =[self.databasePath UTF8String];

        if(sqlite3_open(dbpathss, &studs)==SQLITE_OK)

            char *sqlQuery ="create table if not exists emp(name text,city text,img blob)";

            if(sqlite3_exec(studs, sqlQuery, nil, nil, &ermsgss)!=SQLITE_OK)
                NSLog(@"Failed to create table:");
            
            else
                NSLog(@"Successfully to create table:");
            

        
        sqlite3_close(studs);
    
    return isSuccess;


-(void)insertDatabaseValue:(DataManagers *)getInserted

    dbPath = [self.databasePath UTF8String];

    if(sqlite3_open(dbPath, &studs)==SQLITE_OK)

        NSString *sqlQuery=[[NSString alloc]initWithFormat:@"insert into emp values(?,?,?)"];

        const char *_sqlQuery=[sqlQuery UTF8String];

        if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK)

            sqlite3_bind_text(ermsg, 1, [getInserted.userName UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(ermsg, 2, [getInserted.cityName UTF8String], -1, SQLITE_TRANSIENT);

            NSData *jpegData =[[NSData alloc]init];

            NSData *imgeData =UIImageJPEGRepresentation(getInserted.profileImg, 0.85f);

            UIImage *imgesData =[UIImage imageWithData:imgeData];

            CGRect rect = CGRectMake(0, 0, 185, 150);

            UIGraphicsBeginImageContext(rect.size);

            [imgesData drawInRect:rect];

            UIImage *img =UIGraphicsGetImageFromCurrentImageContext()
            ;
            UIGraphicsEndImageContext();

            jpegData = UIImageJPEGRepresentation(img, 0.01f);

            sqlite3_bind_blob(ermsg, 3, [jpegData bytes], [jpegData length], SQLITE_TRANSIENT);

            if(sqlite3_step(ermsg)==SQLITE_DONE)

                NSLog(@"Successfully inserted into db:");
            
            else 
                NSLog(@"Error %s",sqlite3_errmsg(studs));
            
        

        sqlite3_close(studs);
        sqlite3_finalize(ermsg);
    


-(NSMutableArray*)getAllData 

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

    dbPath = [self.databasePath UTF8String];

    if(sqlite3_open(dbPath, &studs)==SQLITE_OK)

        NSString *sqlQuery =[[NSString alloc]initWithFormat:@"select * from emp"];

        const char *_sqlQuery =[sqlQuery UTF8String];

        if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK)

            while (sqlite3_step(ermsg)==SQLITE_ROW) 

                DataManagers *mgr =[[DataManagers alloc]init];

                NSString *_Firstname = (const char*)sqlite3_column_text(ermsg, 0) ? [NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 0)]:nil;

                mgr.userName = _Firstname;

                NSString *lastName =(const char*)sqlite3_column_text(ermsg, 1)?[NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 1)]:nil;

                mgr.cityName = lastName;

                int imgBytes = sqlite3_column_bytes(ermsg, 2);

                UIImage *img =[UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(ermsg, 2) length:imgBytes]];

                mgr.profileImg = img;

                [array addObject:mgr];
            
        
    
    return array;

【讨论】:

以上是关于如何在 NSDictionary 中访问本地 JSON 文件响应以在 UITableView 中显示?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 PLIST 中访问嵌套的 NSDictionary?

如何在保持成员之间的链接的同时访问 NSDictionary 的另一个成员中的成员

如何使用 RKMappingOperation 将本地 NSDictionary 映射到自定义对象?

如何使用保留关键字访问 NSDictionary 元素?

如何在Node js中限制一个客户端一次在本地访问一个文件

如何在浏览器中访问远程 node.js 应用程序,而不是在本地主机上