mardi 21 juillet 2015

Sqlite3 to NSMutableDictionary to JSON

I'm fairly new at objective c and my objective is to retrieve information from an sqlite database , and make a perfect well formed JSON.

My dd schema is simple:

| ID | latitude  |  longitude

and the expected valid JSON should look like this:

{
  "ID1" : {  
      "latitude" : "lat from id1",
      "longitude" : "long from id1"
   },
  "ID2" : {
      "latitude" : "lat from id2",
      "longitude" : "long from id2"
   } etc...
}

Without worth mentioning the loop through the database, i recreate manually what would give the while (sqlite3_step(statement) == SQLITE_ROW) .

NSMutableDictionary *json= [[NSMutableDictionary alloc] init];
NSMutableDictionary *coords= [[NSMutableDictionary alloc] init];

[coords setObject:@"52.87652" forKey:@"latitude"];
[coords setObject:@"2.3339" forKey:@"longitude"];

[json setObject:coords forKey:@"1"];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
NSLog(@"\n%@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

This example give me the correct output:

{
  "1" : {
    "longitude" : "2.3339",
    "latitude" : "52.87652"
  }
}

but it fail yet im trying to add an another, so basically my request is if anyone could show me a snippet on how to recreate this structure above with a loop, as i might have hundreds for records in my database.

Thanks a lot for your help.

Steve

Aucun commentaire:

Enregistrer un commentaire