IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Objective-C Discussion :

Problème NSData vers NSString [Objective-C]


Sujet :

Objective-C

  1. #1
    Membre du Club
    Inscrit en
    Avril 2009
    Messages
    105
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 105
    Points : 62
    Points
    62
    Par défaut Problème NSData vers NSString
    Bonjour à tous,

    je récupère des données dans un objet NSData que je transforme en NSString.
    Je passe ma string dans un tableau que je veux parcourir.

    Mon problème, je n'arrive pas à récupérer les chaines que j'ai stocké dans mon tableau, voici le code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
     
     
    NSData *response = [[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]autorelease];
     
    	NSString *json_string = [[[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding]autorelease];
     
    	NSString *clean = [[[[[[[[json_string stringByReplacingOccurrencesOfString:@"," withString:@""]
    							 stringByReplacingOccurrencesOfString:@"null]" withString:@""]
    							stringByReplacingOccurrencesOfString:@"[" withString:@""]
    						   stringByReplacingOccurrencesOfString:@":" withString:@""]
    						  stringByReplacingOccurrencesOfString:@"\"\"" withString:@"\""]
    						 stringByReplacingOccurrencesOfString:@"}{" withString:@","]
    						stringByReplacingOccurrencesOfString:@"{" withString:@""]
    					   stringByReplacingOccurrencesOfString:@"}" withString:@""];
     
     
     
    	pageResultat=[[[NSMutableArray alloc]init]autorelease];
    	pageResultat=[clean componentsSeparatedByString:@"\""];
     
    	NSInteger compteurTableauJson =1;
    	NSMutableString * chaineTest=[[[NSMutableString alloc] init]autorelease];
     
    	while (compteurTableauJson <= [pageResultat count]) {
    		[chaineTest setString:[pageResultat objectAtIndex:compteurTableauJson]]; // L'erreur est ici !!!!!!!!!!!!!!!!!!!!!
    			if([chaineTest isEqualToString:@"id_bien"]){
    				[self.afficheResultat addObject:[[[bien alloc] initWithId:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+1] andCp:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+3] andSurf:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+5] andPrix:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+7] andPieces:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+9] andCategorie:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+11]]autorelease]];
    				compteurTableauJson+=12;
     
    			}
     
    			compteurTableauJson++;
    		}
     
    	[sacTest release];
    Merci d'avance pour le temps que vous consacrerez à m'aider.

    Cordialement Jason T.

  2. #2
    Expert confirmé
    Homme Profil pro
    Inscrit en
    Septembre 2006
    Messages
    2 937
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 2 937
    Points : 4 358
    Points
    4 358
    Par défaut
    les index des objets dans un NSArray vaut de 0 à N-1 pas de 1 à N…

  3. #3
    Membre du Club
    Inscrit en
    Avril 2009
    Messages
    105
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 105
    Points : 62
    Points
    62
    Par défaut
    J'ai corrigé mes erreurs mon application ne plante plus au chargement de cette page. La boucle présente dans le viewdidload est entièrement parcouru.

    Mais, j'ai encore un petit problème rien ne s'affiche dans mes cellules ...
    J'ai testé un affichage d'une variable de ma classe "bien" à la place du titre et cela m'a affiché "null".

    Voici le code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
     
     
    NSString * maRequete = [[[NSString alloc] initWithFormat:@"http://www.incomm.fr/partenaires/test_iphone/json.php?codePostal=%d&surfaceMin=%d&surfaceMax=%d&loyerMin=%d&loyerMax=%d&chambre=%d&typeDeBien=%d"
    							 ,[ [ recherche sharedRecherche ] codePostal ], [ [ recherche sharedRecherche ] surfaceMin ],[ [ recherche sharedRecherche ] surfaceMax ]
    							 ,[ [ recherche sharedRecherche ] loyerMin ], [ [ recherche sharedRecherche ] loyerMax ],[ [ recherche sharedRecherche ] chambre ],[ [ recherche sharedRecherche ] typeDeBien ]]retain];
     
    	NSURLRequest *request = [[NSURLRequest requestWithURL:[NSURL URLWithString:maRequete]]retain];
     
    	NSData *response = [[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]retain];
     
    	NSString *json_string = [[[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding]retain];
     
    	NSString *clean = [[[[[[[[[json_string stringByReplacingOccurrencesOfString:@"," withString:@""]
    							 stringByReplacingOccurrencesOfString:@"null]" withString:@""]
    							stringByReplacingOccurrencesOfString:@"[" withString:@""]
    						   stringByReplacingOccurrencesOfString:@":" withString:@""]
    						  stringByReplacingOccurrencesOfString:@"\"\"" withString:@"\""]
    						 stringByReplacingOccurrencesOfString:@"}{" withString:@","]
    						stringByReplacingOccurrencesOfString:@"{" withString:@""]
    					   stringByReplacingOccurrencesOfString:@"}" withString:@""]retain];
     
    	pageResultat=[[[NSMutableArray alloc]init]retain];
    	pageResultat=[clean componentsSeparatedByString:@"\""];
     
    	NSInteger compteurTableauJson =0;
    	NSMutableString * chaineTest=[[[NSMutableString alloc] initWithString:(NSString *)[pageResultat objectAtIndex:compteurTableauJson]]retain];
    	while (compteurTableauJson <= [pageResultat count]-1) {
     
    		[chaineTest setString:[pageResultat objectAtIndex:compteurTableauJson]];
    			if([chaineTest isEqualToString:@"id_bien"]){
    				self.title=@"TIMMY!!!!";
    				[self.afficheResultat addObject:[[[bien alloc] initWithId:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+1] andCp:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+3] andSurf:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+5] andPrix:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+7] andPieces:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+9] andCategorie:(NSString *)[pageResultat objectAtIndex:compteurTableauJson+11]]autorelease]];
    				compteurTableauJson+=12;
     
    			}
     
    			compteurTableauJson++;
    		}
     
     
    	[self.myTableResultat reloadData]; // On charge les données dans la vue en table (TableView)	
     
    }
    Cordialement Jason T.

  4. #4
    Expert confirmé
    Homme Profil pro
    Inscrit en
    Septembre 2006
    Messages
    2 937
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 2 937
    Points : 4 358
    Points
    4 358
    Par défaut
    il existe des libraires OpenSource de traitement du JSON…
    (exemple: http://json-framework.googlecode.com...aceSBJSON.html)

    çà serait certainement plus simple que d'essayer de réinventer tout…
    parser du JSON revient alors à faire quelque chose du genre :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    NSObject *resultAsObject = [parser objectWithString:json_string error:&error];

  5. #5
    Membre du Club
    Inscrit en
    Avril 2009
    Messages
    105
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 105
    Points : 62
    Points
    62
    Par défaut
    J'ai essayé de parser l'objet JSON mais je n'arrive toujours pas à récupérer mes données...

    Mon objet JSON ressemble à ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
     
    [{"id_bien":"101","cp_offre":"47120"},{"id_bien":"5","cp_offre":"47120"}]
    Je voudrais stocker mes données dans un tableau dans lequel chaque case contiendrait un NSDictionary d'un bien.

    Je n'y arrive pas du tout. Si quelqu'un pouvait m'aider ce serait sympa.
    Si j'arrive à enregistrer ces données je n'ai plus qu'à les afficher et mon projet sera fini.

    Merci à tout ceux qui m'auront consacré de leur temps.

  6. #6
    Expert confirmé
    Homme Profil pro
    Inscrit en
    Septembre 2006
    Messages
    2 937
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 2 937
    Points : 4 358
    Points
    4 358
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
     
     
    #import <Foundation/Foundation.h>
    #import "JSON.h"
     
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	NSString *jsonString = @"[{\"id_bien\":\"101\",\"cp_offre\":\"47120\"},{\"id_bien\":\"5\",\"cp_offre\":\"47120\"}]" ;
    	NSError *error = nil ;
     
    	SBJSON *jsonParser = [[SBJSON alloc] init];
    	NSArray *array = [jsonParser objectWithString:jsonString error:&error];
     
    	if (error != nil) {
    		NSLog(@"*** error %@ parsing %@", error, jsonString) ;
    	}
     
        NSLog(@"%@", array);
        [pool drain];
        return 0;
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
     
    2010-08-11 12:15:40.528 TestParsingJSON[17436:a0f] (
            {
            "cp_offre" = 47120;
            "id_bien" = 101;
        },
            {
            "cp_offre" = 47120;
            "id_bien" = 5;
        }
    )

  7. #7
    Membre du Club
    Inscrit en
    Avril 2009
    Messages
    105
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 105
    Points : 62
    Points
    62
    Par défaut
    Effectivement, j'ai essayé ton code et c'est parfait pour accéder aux données.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    NSLog(@"%@",[[array objectAtIndex:0] objectForKey:@"cp_offre"]);
    Mais je ne comprends pas, pourquoi ca ne marche pas pur mon affichage en table:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //ce que l'on affiche dans les cellules de la vue en table
     
     
        static NSString *CellIdentifier = @"Cell";
     
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];// Récupère une cellule réutilisable, retourne nil sinon.
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; //Définit l'identifiant de la cellule
        }
    	cell.textLabel.text=[[afficheResultat objectAtIndex:indexPath.row] objectForKey:@"categorie"];
    	cell.detailTextLabel.text=[[afficheResultat objectAtIndex:indexPath.row] objectForKey:@"cp_offre"];
    	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    	return cell;
    }
    J'ai copié mon tableau dans le tableau afficheResultat.
    J'ai testé si ca s'affiché dans la console, ca fonctionne.
    Je ne comprends pas mes cellules apparaissent vides...

  8. #8
    Membre du Club
    Inscrit en
    Avril 2009
    Messages
    105
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 105
    Points : 62
    Points
    62
    Par défaut
    Personne n'a d'idée sur le fait que ma tableView soit blanche alors que tout fonctionne ?

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. problème hyperlien vers onglet
    Par phal2ip dans le forum Macros et VBA Excel
    Réponses: 6
    Dernier message: 23/08/2008, 13h21
  2. Problème xml vers table oracle
    Par soft1982 dans le forum Import/Export
    Réponses: 1
    Dernier message: 03/08/2008, 16h07
  3. [1.x] problème url vers dossier images
    Par NVCyril dans le forum Symfony
    Réponses: 1
    Dernier message: 02/05/2008, 13h33
  4. [DEBUTANT] Problème DNS vers sites
    Par tripper.dim dans le forum Windows Serveur
    Réponses: 7
    Dernier message: 17/10/2007, 12h14
  5. problème lien vers Applet
    Par GregHory dans le forum Applets
    Réponses: 1
    Dernier message: 10/04/2006, 18h05

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo