将Json解析为对象给出" null"值

时间:2018-03-26 07:40:50

标签: objective-c nsjsonserialization

无法将此json数据解析为object。我尝试使用其他URL的相同代码,正常工作。请建议我做错了什么?

-(void)callAPI{
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https:s.json"]];
    NSError *error=nil;
    id response=[NSJSONSerialization JSONObjectWithData:data options:
                 NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];

    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    } else {

        NSLog(@"%@",response);}}

输出无法读取数据,因为格式不正确。

1 个答案:

答案 0 :(得分:0)

我为你的问题找到了非常完美的解决方案,现在工作正常。请查看以下答案

- (void)callAPI 
{

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setHTTPMethod:@"GET"];
  [request setURL:[NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
  [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
  ^(NSData * data,
    NSURLResponse * response,
    NSError * error) {
      NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
      NSLog(@"jsonString is: %@", jsonString);
      NSData *dataCon = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
      id jsonVal = [NSJSONSerialization JSONObjectWithData:dataCon options:0 error:nil];
      if([jsonVal isKindOfClass:[NSDictionary class]]) {
          NSLog(@"The response starts with NSDictionary");
          NSArray *arrJsonVal = [jsonVal objectForKey:@"rows"];
          NSMutableArray *arrTitle = [[NSMutableArray alloc]init];
          NSMutableArray *arrDesc = [[NSMutableArray alloc]init];
          NSMutableArray *arrImage = [[NSMutableArray alloc]init];
          for(NSDictionary *dict in arrJsonVal) {
              NSString *strTitle = [dict objectForKey:@"title"];
              NSString *strDesc = [dict objectForKey:@"description"];
              NSString *strImage = [dict objectForKey:@"imageHref"];

              [arrTitle addObject:strTitle];
              [arrDesc addObject:strDesc];
              [arrImage addObject:strImage];
          }
          NSLog(@"arrTitle is - %@",arrTitle);
          NSLog(@"arrDesc is - %@",arrDesc);
          NSLog(@"arrImage is - %@",arrImage);

      }else {
          NSLog(@"The response starts with NSArray");
      }
  }] resume];

}

印刷结果

enter image description here  enter image description here

之后

enter image description here

然后数组结果

enter image description here enter image description here

最后结果是

enter image description here

相关问题