0

我是 ObjectiveC 的新手,我在从 url 检索 JSON 类型时遇到问题,该 url 代表一个为返回 JSON 和 XML 而构建的 web 服务,当我尝试从 url 使用 web 服务时,结果是 XML,我需要的是确定请求中返回数据的类型为 JSON。顺便说一句,我确信 Web 服务会返回 XML 和 JSON。

这是我获取 XML 的代码:

NSURL *url = [[NSURL alloc] initWithString:@"http://192.168.1.1:8080/test2/eattel/restaurants"];
NSString *result=[[NSString alloc] initWithContentsOfURL:url];
NSLog(@"%@",result);

结果是:

   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <restaurantImpls>
<Resstaurant Name="Abo Alshamat" PhoneNumber="0991992994" MobileNumber="0991992993" LastName="Shame" ID="1" FirstName="Samer"/>
<Resstaurant Name="AL-Kamal" PhoneNumber="0992993995" MobileNumber="0992993994" LastName="Ali" ID="2" FirstName="Ahmad"/>
<Resstaurant Name="Abo-MAhmoud" MobileNumber="0993377800" ID="12"/>
<Resstaurant Name="Four Season" PhoneNumber="0993994996" MobileNumber="0993994995" LastName="Ammar" ID="3" FirstName="William"/>
<Resstaurant Name="uuuuu" MobileNumber="0999555777" LastName="William" ID="20" FirstName="Ammar"/>
<Resstaurant Name="NewOneFromI2" MobileNumber="0999888777" ID="18"/>
<Resstaurant Name="JOURY" PhoneNumber="0999999998" MobileNumber="0999998997" ID="4"/>
<Resstaurant Name="TestTestRestaurant,Ammar,Hamed" MobileNumber="202020" ID="19"/>
</restaurantImpls>

感谢您的时间。

4

1 回答 1

3

我们无法从我们的请求中设置响应数据类型。从服务器设置响应。根据您的描述(Web 服务返回 XML 和 JSON),我猜您需要发布一个状态变量,该变量显示返回状态,如isXML. 这只是我的猜测。您需要联系服务器端程序员了解此请求的实现。

编辑 试试下面的代码

responseData = [[NSMutableData alloc]init];
NSURL *url = [[NSURL alloc] initWithString:@"http://192.168.1.1:8080/test2/eattel/restaurants"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"application/json" forHTTPHeaderField:@"accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
(void)[NSURLConnection connectionWithRequest:req delegate:self];

然后你需要实现 NSURLConnection Delegates。

#pragma mark - NSURLConnection Delegates

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  {

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response   {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {
    [responseData appendData:data]; 
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection    {

    NSString *responseString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",responseString);

}
于 2013-11-12T10:20:51.910 回答