Interroger un fichier Json avec Xcode

jeudi 29 novembre 2012
Pour les applications mobiles, il est préconiser d’utiliser Json à la place de Xml car il est plus léger que son prédécesseur. Il plus intéressant de faire transiter des données via notre mobile avec du Json afin de limiter le volume de data qui reste cher en Belgique :-). Pour parser du contenu json il existe un framework natif depuis IOS 5 => NSJSONSerialisation. Ci dessous vous trouverez un exemple d’utilisation:
NSError *error = nil;
NSString *filepath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filepath];
if (jsonData) {
  id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
  if (error) {
    NSLog(@"error is %@", [error localizedDescription]);
    // Handle Error and return return;
  }
  NSArray children = [jsonObjects objectForKey:@"tag"]; 
} 
else { 
// Handle Error 
} 
Il existe aussi un framework non natif facile d’utilisation. Cliquez sur le lien pour télécharger le framework. Voici un exemple d’utilisation:
#import "JSON.h";
NSString *filepath=[[NSBundle mainBundle] pathForRessource:@"test" ofType:@"json"];
NSString *myJSON= [[NSString alloc] initWithContentsOfFile:filepath NSUTF8StringEncoding error:NULL];
//Parsing du json
NSDictionnary *json = [myJSON JSONValue];

Tags: Développement , IOS , Json , Objective C , Xcode , XML