在ios中也經常需要操作json object,特別是與服務端交互的時候
項目中數據庫訪問用了FMDB組件,有一個很方便的API,可以直接返回一個NSDictionary
FMResultSet *rs = [db executeQuery:sql, latestObj, nowObj, latestObj, nowObj]; while ([rs next]) { [result addObject:[rs resultDictionary]]; }
[middle appendString:[row description]];
NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:row options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
還有另一個相反的API,可以從NSData得到NSDictionary,然後就可以調用NSDictionary的API來操作json object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSError *error = nil; NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];// 包含兩個key,code和result,或者code和error NSNumber *code = [jsonArray objectForKey:@"code"]; if([code intValue] == 0){ NSLog(@"添加備份記錄成功", nil); }