2011-07-27 5 views
1

i créer serveur php et j'appeler cette fonction dans mon objectif cJSON Parse chaîne

public function getCOMPAINs(){ 

     $query = "SELECT COMPAINCOMPAIN_ID FROM COMPAIN_USER WHERE USERUSER_ID = '$this->USER_ID'"; 
      $MyConnection = new MyConnection(); 
     $result = mysql_query($query,$MyConnection->Connection) or die(mysql_error()); 
    while($obj=mysql_fetch_object($result)) { 
     $res[] = array('COMPAIN_ID' => $obj->COMPAINCOMPAIN_ID); 
    } 
    return json_encode($res); 



    } 

si je tente appeler cette fonction avec php je peux montrer cette réponse

array(2) { 
    [0]=> 
    array(1) { 
    ["COMPAIN_ID"]=> 
    string(2) "44" 
    } 
    [1]=> 
    array(1) { 
    ["COMPAIN_ID"]=> 
    string(2) "46" 
    } 
} 

Comment puis-je analyser ces données de réponse avec JSON? i essayer de faire cette solution mais en utilisant XML

- (NSMutableData *)sendRequestCompains{ 

     NSMutableString *sRequest = [[NSMutableString alloc] init]; 
     [sRequest appendString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"]; 
     [sRequest appendString:@"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"]; 
     [sRequest appendString:@"<soap:Body>"]; 
     [sRequest appendString:@"<getCOMPAINs xmlns=\"http://tempuri.org/PlatformService/method\">"]; 
     [sRequest appendString:@"<Id_USR>"]; // any attribute 
     [sRequest appendString:@"1"]; // attribute value 
     [sRequest appendString:@"</Id_USR>"]; 
     [sRequest appendString:@"</getCOMPAINs>"]; 
     [sRequest appendString:@"</soap:Body>"]; 
     [sRequest appendString:@"</soap:Envelope>"]; 


     NSURL *ServiceURL = [NSURL URLWithString:@"http://79.249.37.1/server_comp.php"]; 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:ServiceURL]; 
     [request addValue:@"text/xml; charset:UTF-8" forHTTPHeaderField:@"Content-Type"]; 
     [request addValue:@"http://79.249.37.1/server_comp.php/getCOMPAINs" forHTTPHeaderField:@"SOAPAction"]; 
     [request setHTTPMethod:@"POST"]; 
     [request setHTTPBody:[sRequest dataUsingEncoding:NSUTF8StringEncoding]]; 
     NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
     if (conn) { 
      data = [[NSData data] retain]; 
      NSLog(@"Connection success"); 
      [NSURLConnection connectionWithRequest:request delegate:self]; 
      NSError *WSerror; 
      NSURLResponse *WSresponse; 

     data = [NSURLConnection sendSynchronousRequest:request returningResponse:&WSresponse error:&WSerror]; 
      NSLog(@"slt%d",[data length]); 
     } 






     return data; 
    } 

i essayer cette solution, mais pas WOR k

NSData * webData=[[NSMutableData alloc] initWithData:self.sendRequestCompains]; 



    // Create new SBJSON parser object 
    SBJSON *parser = [[SBJSON alloc] init]; 



    NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding]; 

    NSArray *statuses = [parser objectWithString:json_string error:nil]; 

    for (NSDictionary *status in statuses) 
    { 

     NSLog(@"%@", [status objectForKey:@"0"]); 
    } 


    the response recived from server 
<?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:getCOMPAINsResponse xmlns:ns1="http://tempuri.org/PlatformService/method"><COMPAIN xsi:type="xsd:string">[{&quot;COMPAIN_ID&quot;:&quot;44&quot;},{&quot;COMPAIN_ID&quot;:&quot;46&quot;}]</COMPAIN></ns1:getCOMPAINsResponse></SOAP-ENV:Body></SOAP-ENV:Envelope> 

i essayer cette solution, mais fonctionne pas

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL 

URLWithString:@"http://79.249.37.1/server_comp.php/getCOMPAINs.json?userId=1"]];

// execution de la requête et récupération du JSON via un objet 

NSData NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// On récupère le JSON en NSString depuis la réponse 
    NSString *json_string = [[NSString alloc] initWithData:response 

encoding:NSUTF8StringEncoding];

// on parse la reponse JSON 
    NSArray *statuses = [parser objectWithString:json_string 

error:nil];

for (NSDictionary *status in statuses) 
    { 
     // on peut recuperer les valeurs en utilisant objectForKey à 

partir du status qui est un NSDictionary // on log le tweet et le nom de l utilisateur NSLog(@"%@", [status objectForKey:@"COMPAIN_ID"]); }

+0

Ajoutez la réponse de votre serveur (le JSON, pas la sortie PHP pritn_r!) À la question s'il vous plaît! L'un de vos commentaires ci-dessous dit 'recive json dans la chaîne xml' et cela n'a aucun sens - nous avons besoin de plus d'informations. – deanWombourne

+0

cela le includ JSON en réponse [{" COMPAIN_ID ": }, {" COMPAIN_ID ": }] –

+0

aucune aide pour moi? –

Répondre

3

Vous voulez utiliser JSON pour analyser la réponse, mais la la réponse est enveloppée dans du XML.

Vous avez deux options:

1) parser le XML pour obtenir le JSON, puis Parse que JSON

2) Demandez au serveur de ne pas envelopper votre réponse dans le XML, il suffit de retourner le JSON .

Vous semblez parler au serveur avec SOAP (à partir de sendRequestCompains) - il y a peu de chance que si vous faites une requête SOAP, il retournera un objet JSON! Je pense que votre meilleur pari serait l'option (1).

Cependant, si vous avez le contrôle sur votre serveur je cesser d'utiliser SOAP du tout et obtenir la réponse à quelque chose comme

http://79.249.37.1/server_comp.php/getCOMPAINs.json?Id_USR=1 

Je passe les paramters comme params URL, non pas comme SOAP objet. Je spécifie également que je suis intéressé par une réponse json avec le .json à la fin de l'URL.

+0

thx bro je veux essayer l'option 2, vraiment je ne veux pas utiliser XML –

+0

haw je peux demander à mon serveur de ne pas encapsuler la réponse dans le XML et utiliser juste retourner le JSON –

+0

haw je peux obtenir mon Id_USR = 1 dans ma fonction getCOMPAINs? –

0

Avant cette ligne:

NSArray *statuses = [parser objectWithString:json_string error:nil]; 

Ajouter ces lignes:

json_string = [json_string stringByReplacingOccurancesOfString:@"<?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:getCOMPAINsResponse xmlns:ns1="http://tempuri.org/PlatformService/method"><COMPAIN xsi:type="xsd:string">" withString:@""]; 
json_string = [json_string stringByReplacingOccurancesOfString:@"</COMPAIN></ns1:getCOMPAINsResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>" withString:@""]; 

Ceci est hardcoded, vous devez donc être sûr que cela ne changera pas.

Ce qui reste est le json_string, mais codé avec des entités html. Pour décoder, ajoutez cette classe à votre projet:
https://discussions.apple.com/message/8064367#8064367

Et ajouter une autre ligne avant NSArray *statuses ....

json_string = [[[MREntitiesConverter alloc] init] convertEntiesInString:json_string];