json解析字符串

时间:2011-07-27 10:28:54

标签: objective-c json

我创建了php服务器,我在我的目标c

中调用了这个函数
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);



  }

如果我尝试用php调用此函数,我可以显示此响应

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

如何使用Json解析此响应数据?我尝试使用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;
    }

我尝试这个解决方案但没有工作

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>

我尝试这个解决方案但没有工作

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
     

编码:NSUTF8StringEncoding];

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

误差:无];

  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”]);         }

3 个答案:

答案 0 :(得分:3)

您希望使用JSON来解析响应,但响应包含在某些XML中。

您有两种选择:

1)解析XML以获取JSON,然后将其解析为JSON

2)要求服务器不要将您的响应包装在XML中,只需返回JSON。

您似乎正在使用SOAP(来自sendRequestCompains)与服务器通信 - 如果您发出SOAP请求它将返回一个JSON对象的可能性很小!我认为你最好的选择是选项(1)。

但是,如果您可以控制您的服务器,我会停止使用SOAP并让它响应

之类的内容
http://79.249.37.1/server_comp.php/getCOMPAINs.json?Id_USR=1

我将这些参数作为URL参数传递,而不是作为SOAP对象传递。我还指定我对URL末尾的 .json 的json响应感兴趣。

答案 1 :(得分:1)

答案 2 :(得分:0)

在此之前:

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

添加以下行:

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:@""];

这是硬编码的,所以你需要确保这不会改变。

剩下的是json_string,但是用html实体编码。要对其进行解码,请将此类添加到项目中:
https://discussions.apple.com/message/8064367#8064367

NSArray *statuses ...之前添加另一行。

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