Json的回应是错误的数据

时间:2014-05-10 04:35:11

标签: ios json nsurlconnection nsmutableurlrequest

我使用NSURLConnection调用webservice字符串,我在NSURLConnection的成功方法中收到了错误的数据,但是如果我在浏览器中加载相同的URL我会得到正确的响应。我正在使用下面的代码。

    NSData *mydata=[srtRes dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e;
    NSMutableArray *returnArry =[[NSMutableArray alloc]init];
    returnArry = [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingMutableContainers error:&e];

如何解决此问题。请提出建议和答案。

1 个答案:

答案 0 :(得分:1)

试试这个:

  // In .h class
  @property (nonatomic,retain) NSMutableData *responseData;
  @property (nonatomic, retain) NSMutableArray *temp_arr;

  // In .m class
  @synthesize responseData;
  @synthesize temp_arr;

  - (void)viewDidLoad
  {
     NSString *urlString=@"http://your urls";
     self.responseData=[NSMutableData data];
     NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
     NSLog(@"connection====%@",connection);
  }

JSON解析的委托方法:

 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 {
    [self.responseData setLength:0];
 }
 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 {
    [self.responseData appendData:data];
 }  
 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
    self.responseData=nil;
 }
 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
 {
     NSArray * returnArry = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
      NSDictionary *nameDic = nil;
     for (int i = 0 ; i < [returnArry count]; i++)
     {
        nameDic = [returnArry objectAtIndex:i];
        [self.temp_arr addObject:[nameDic objectForKey:@"name"]];  // According your key you have to save data in temp_arr.
     }
 }

如果有任何疑问请告诉我,请关注此事。)