-1

I am creating iOS app which uses SQLite DB. I have created Table As:

const char *sql_stmt = "CREATE TABLE IF NOT EXISTS ORDERTABLE (ID INTEGER PRIMARY KEY AUTOINCREMENT, ITEMDESC BLOB)";

and then I have to insert self.selectedItemsDictnory Dictionary into ItemDESC i am inserting as :

NSData *data = [NSJSONSerialization dataWithJSONObject:self.selectedItemsDictnory options:NSJSONWritingPrettyPrinted error:nil];

NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO ORDERTABLE(ITEMDESC)VALUES( \"%@\");",data];

Upto this it is successfully done.

Now i have to retrieve this dictionary in same format

what i am doing is :

if (sqlite3_prepare_v2(orderDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK) {

    while (sqlite3_step(statement) == SQLITE_ROW) {
        int uniqueId = sqlite3_column_int(statement, 0);

        const void *blob = sqlite3_column_blob(statement, 1);
        NSInteger bytes = sqlite3_column_bytes(statement, 1);
        NSData *data = [NSData dataWithBytes:blob length:bytes];
        NSError *error;

        NSMutableString *jsonObject=[NSJSONSerialization
                                         JSONObjectWithData:data
                                         options:NSJSONReadingMutableLeaves
                                         error:&error];
        NSLog(@"jsonObject is %@ with error %@",jsonObject, error);

    }

    sqlite3_finalize(statement);
    sqlite3_close(orderDB);
}

And I am getting Error as

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
Sulabh
  • 11
  • 2
  • 6
  • and my NSDictionary which i am inserting is as example : po self.selectedItemsDictnory $1 = 0x07184170 { Light = 50; Pasta = 220; } I tried to search this error. i found that my JSON which i am retrieving is actually not in a JSON format. Please provide your Inputs thanks – Sulabh Apr 29 '13 at 13:24

1 Answers1

1

You are not formatting the JSON property. In this:

NSData *data = [NSJSONSerialization dataWithJSONObject:self.selectedItemsDictnory options:NSJSONWritingPrettyPrinted error:nil];

Now you have a data blob, not a string, but below, you treat it as a string:

NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO ORDERTABLE(ITEMDESC)VALUES( \"%@\");",data];

If you want a string:

NSString *jsonString = [NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO ORDERTABLE(ITEMDESC)VALUES( \"%@\");",jsonString];
David H
  • 40,852
  • 12
  • 92
  • 138