【问题标题】:json parse stringjson解析字符串
【发布时间】:2011-07-27 10:28:54
【问题描述】:

我创建 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 *响应 = [NSURLConnection sendSynchronousRequest:request returnedResponse: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"]); }

【问题讨论】:

  • 请将来自您服务器的响应(JSON,而不是 PHP pritn_r 输出!)添加到问题中!下面的一个 cmets 说“在 xml 字符串中接收 json”,这根本没有意义 - 我们需要更多信息。
  • 这个 json 包含在响应中 [{"COMPAIN_ID":"44"},{"COMPAIN_ID":"46"}]
  • 那里根本没有 XML,你为什么说 'xml string'?
  • 因为收到的响应以 开头
  • 所以您在之前的评论中发布的代码不是完整的回复!为什么不能解析 XML 得到 JSON,然后只解析 JSON?

标签: objective-c json


【解决方案1】:

您想使用 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 响应感兴趣。

【讨论】:

  • 我可以要求我的服务器不要将响应包装在 XML 中并使用只返回 JSON
  • 我可以在我的函数 getCOMPAINs 中获得我的 Id_USR=1 吗?
  • getCOMPAINs 是我在服务器中的功能,你的意思是 getCOMPAINs.json?
  • 我会坚持选项 1。您已经快到了,您只需要从输入中去除额外的 XML,然后从您的 JSON 中解码 html-entities。
  • @Tim van Elsloo - 我也支持选项 (1) - 解析 XML 应该非常简单;与他在这个问题上的所有论点相比,解析它所花费的时间会更少;)
【解决方案2】:

看到这个问题:Native JSON support in iOS?,指的是这个链接:http://code.google.com/p/json-framework/

【讨论】:

  • 我在 xml 字符串中接收到 json 的问题
  • 我不使用 json 文件,但我从我的服务器接收字符串
  • 我可以将 sendRequestCompains 更改为使用 json 吗?
  • 对我来说,响应看起来像 SOAP。 sudzc.com 在生成一个解析 SOAP 响应的 iPhone 项目方面做得很好。从那里开始,您可以使用 JSON 解析器。或者看这里:stackoverflow.com/questions/5966401/…
  • 如果我不想用肥皂她只用json我可以这样做吗?
【解决方案3】:

在这一行之前:

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-entities 编码。要对其进行解码,请将此类添加到您的项目中:
https://discussions.apple.com/message/8064367#8064367

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2021-04-25
    • 2014-07-22
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多