从 json 创建数组并将数组保存在 objective C iOS 中的 SQLite 列中

Make arrays from json and save arrays in columns of SQLite in objective C iOS

我正在从我的 json file 中检索数据,它包含 sunrisesunsetmidnighttimings。我想制作 array for sunrisearray for sunsetarray for midnight。并将我的数组保存在 SQLite 中的 sunriseColumnsunsetColumnmidnightColumn 中。

但是我有点困惑我怎样才能以正确的方式做到这一点。

我的 ViewDidLoad()

- (void)viewDidLoad {
[super viewDidLoad];

[self saveinDatabase];

NSURL *url = [NSURL fileURLWithPath:@"/Users/macbook/Desktop/Test/Test/myFile.json"];
NSString *fileContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Json data is here %@", fileContent);

在字典中保存数据

NSArray *data = [[theFeedString JSONValue] objectForKey:@"data"];
for (NSDictionray *dict in data) {
NSString *timings = [[dict objectForKey:@"timings"] intValue];
NSArray *sunriseArray = [objectForKey:@"sunrise"]
NSArray *sunsetArray = [objectForKey:@"sunset"]
NSArray *midnight = [objectForKey:@"midnight"]
}

在我的控制台中,我从 json 获取所有数据,我的 json 看起来像这样

{
"data": [
{
"timings": {
"Sunrise": "07:14 (PKT)",
"Sunset": "18:15 (PKT)",
"Midnight": "00:45 (PKT)"
}
},
{
"timings": {
"Sunrise": "07:13 (PKT)",
"Sunset": "06:40 (PKT)",
"Midnight": "00:45 (PKT)"
}
}
]
}

一种在SQLite

中存储数据的方法
-(void) saveinDatabase {

NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
docsDir = dirPaths[0];

_dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"mydatabase.db"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:_dbPath] == NO) {

    const char *dbPathagain = [_dbPath UTF8String];

    if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
        char *errorMessage;
        const char *sql_statement = "CREATE TABLE IF NOT EXISTS jsontable(ID integer primary key, sunrise text, sunset text, midnight text)";

        NSLog(@"created table success");

        sqlite3_stmt *statement;
        const char *dbPathagain = [ _dbPath UTF8String];

        if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
            NSString *insertSQLData = [NSString stringWithFormat:@"INSERT INTO jsontable(sunrise, sunset, midnight) VALUES (\"%@\", \"%@\", \"%@\")", sunriseArray, sunsetArray, midnightArray];
            const char *insert_statement = [insertSQLData UTF8String];
            sqlite3_prepare_v2(_DB, insert_statement, -1, &statement, NULL);

            if (sqlite3_step(statement) == SQLITE_DONE) {
                NSLog(@"data added successfully");
                NSLog(@"here is sunrise times %@", sunriseArray);
            }
            else {
                NSLog(@"could not add timings");
            }
            sqlite3_finalize(statement);
            sqlite3_close(_DB);
        }

        if (sqlite3_exec(_DB, sql_statement, NULL, NULL, &errorMessage) != SQLITE_OK) {
            NSLog(@"failed to create table");
        }
        sqlite3_close(_DB);
    }
    else {
        NSLog(@"failed to open db or cretate table");
    }
}
}
}

对您的代码进行以下更改:

将您的 "data" 数组传递给方法。

 NSDictionary *dict = @{
                               @"data": @[
                                       @{
                                           @"timings": @{
                                                   @"Sunrise": @"07:14 (PKT)",
                                                   @"Sunset": @"18:15 (PKT)",
                                                   @"Midnight": @"00:45 (PKT)"
                                                   }
                                           },
                                       @{
                                           @"timings": @{
                                                   @"Sunrise": @"07:13 (PKT)",
                                                   @"Sunset": @"06:40 (PKT)",
                                                   @"Midnight": @"00:45 (PKT)"
                                                   }
                                           }
                                       ]
                               };
     NSArray *arrData = [NSArray arrayWithArray:[dict objectForKey:@"data"]];
    [self saveinDatabase:arrData];

用以下代码替换方法:

-(void) saveinDatabase:(NSArray*) arrData {

    NSString *docsDir;
    NSArray *dirPaths;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
    docsDir = dirPaths[0];

    _dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"mydatabase.db"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:_dbPath] == NO) {

        const char *dbPathagain = [_dbPath UTF8String];

        if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
            char *errorMessage;
            const char *sql_statement = "CREATE TABLE IF NOT EXISTS jsontable(ID integer primary key, sunrise text, sunset text, midnight text)";

            NSLog(@"created table success");

            sqlite3_stmt *statement;
            const char *dbPathagain = [ _dbPath UTF8String];

            if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {


                for (int i=0; i<arrData.count; i++) {

                    NSDictionary *dictTiming = [[arrData objectAtIndex:i] valueForKey:@"timings"];
                    NSString *insertSQLData = [NSString stringWithFormat:@"INSERT INTO jsontable(sunrise, sunset, midnight) VALUES (\"%@\", \"%@\", \"%@\")", [dictTiming objectForKey:@"Sunrise"], [dictTiming objectForKey:@"Sunset"], [dictTiming objectForKey:@"Midnight"]];
                    const char *insert_statement = [insertSQLData UTF8String];
                    sqlite3_prepare_v2(_DB, insert_statement, -1, &statement, NULL);

                    if (sqlite3_step(statement) == SQLITE_DONE) {
                        NSLog(@"data added successfully");
                        NSLog(@"here is sunrise times %@", sunriseArray);
                    }
                    else {
                        NSLog(@"could not add timings");
                    }

                }


                sqlite3_finalize(statement);
                sqlite3_close(_DB);
            }

            if (sqlite3_exec(_DB, sql_statement, NULL, NULL, &errorMessage) != SQLITE_OK) {
                NSLog(@"failed to create table");
            }
            sqlite3_close(_DB);
        }
        else {
            NSLog(@"failed to open db or cretate table");
        }
    }
}