如何使用带有NSJSONSerialization类参考的xcode 4.3.1从URL获取数据

时间:2012-03-17 19:59:57

标签: iphone ios json xcode4.3 nsjsonserialization

我试图绕过NSJSONSerialization Class Reference。由于缺少developer.apple.com网站上的代码示例,我输了。 网上有数以百万计的例子和其他json库,但是我还没有能够使用最新版本的xcode。 (我正在运行:版本4.3.1(4E1019)和在iPhone 5.0.1上测试)

我想使用按钮将json文件中的数据提取到我的iphone中。

让我说我从网址获取数据: http://companyurl/jsonfile.json(标准JSON格式)

jsonfile.json看起来像这样......;

{
  "companylist":   
[
      {
        "company":"Companyname 1",
        "telephone":"1234567890",
        "url":"http:\/\/www.companyname1.com\/",
        "category":"category 1",
        "position":"1",
      },
      {
        "company":"Companyname 2",
        "telephone":"2345678901",
        "url":"http:\/\/www.companyname2.com\/",
        "category":"category 2",
        "position":"2",
      },
      {
        "company":"Companyname 3",
        "telephone":"3456789012",
        "url":"http:\/\/www.companyname3.com\/",
        "category":"category 3",
        "position":"3",
      }
]
}

我在.h和我的.m文件中写什么?

感谢您的帮助! :)

6 个答案:

答案 0 :(得分:15)

NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://your_web_server/your_file...."]];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
                                NSJSONReadingMutableContainers error:&error]; 

NSLog(@"Your JSON Object: %@ Or Error is: %@", response, error);

注意:此代码适用于Xcode 4.2,模拟器上的iOS 5.01和iPad上的5.1设备

答案 1 :(得分:7)

谢谢你们。我想到了。 (......这就是我所做的:)

在我的.m文件中,我添加了以下代码:

    - (IBAction)getDataFromJson:(id)sender {
        NSURL *url = [NSURL URLWithString:@"http://yourwebsite.com/jsonfile.json"];

        NSData *jsonData = [NSData dataWithContentsOfURL:url];


        if(jsonData != nil)
        {
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
            if (error == nil)
                NSLog(@"%@", result);
}
}

在我的.h文件中,我添加了以下代码:

@interface ViewController : UIViewController
- (IBAction)getDataFromJson:(id)sender;

答案 2 :(得分:1)

答案 3 :(得分:1)

永远不要使用dataWithContentsOfURL:以这种方式获取服务器数据。它无法控制,可能会使您的应用程序处于未知状态。您应该至少使用NSURLRequest进行所有网址调用。更好的是,如果你不支持iOS7之前,请使用NSURLSession。

答案 4 :(得分:0)

Tweeting sample app形式的代码示例。

答案 5 :(得分:0)

    jsonDict = [[NSDictionary alloc] init];
    data = [[NSArray alloc] init]; 

      url =[NSURLURLWithString:@"Please Type Your URL  "];


 // Parse the JSON data from the given URL
  - (void) parseJSONWithURL:(NSURL *) jsonURL
  {
// Set the queue to the background queue. We will run this on the background thread to keep
// the UI Responsive.
    dispatch_queue_t queue =    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

// Run request on background queue (thread).
      dispatch_async(queue, ^{
      NSError *error = nil;

    // Request the data and store in a string.
      NSString *json = [NSString stringWithContentsOfURL:jsonURL
                                              encoding:NSASCIIStringEncoding
                                                 error:&error];
      if (error == nil){

        // Convert the String into an NSData object.
        NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];

        // Parse that data object using NSJSONSerialization without options.
        jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

        // Parsing success.
        if (error == nil)
        {
            // Go back to the main thread and update the table with the json data.
            // Keeps the user interface responsive.
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                data= [[jsonDict valueForKey:@"Result"] valueForKey:@"data"];
                [jsonTable reloadData];
            });
        }

        // Parsing failed, display error as alert.
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Uh Oh, Parsing Failed." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];

            [alertView show];
        }
    }

    // Request Failed, display error as alert.
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Request Error! Check that you are connected to wifi or 3G/4G with internet access." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];

        [alertView show];
      }
   });
  }


 // Delegate call back for cell at index path.
  - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];

    if (cell == nil)
    {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
}

// Set the main label as the episode name.
   cell.textLabel.text = [[data objectAtIndex:indexPath.row] objectForKey:@"fullname"];




    NSNumber *seasonNum = [[data objectAtIndex:indexPath.row] objectForKey:@"username"];
    NSNumber *episodeNum = [[data objectAtIndex:indexPath.row] objectForKey:@"location"];
    NSMutableString *seasonEpisodeNum = [NSMutableString stringWithFormat:@"username: %@ ", seasonNum];
    [seasonEpisodeNum appendString:[NSMutableString stringWithFormat:@"location: %@", episodeNum]];
    cell.detailTextLabel.text = seasonEpisodeNum;

    return cell;
    }






  -(int) numberOfSectionsInTableView:(UITableView *) tableView
  {
   return 1;
  }


  - (int) tableView:(UITableView *) tableView numberOfRowsInSection:  (NSInteger)section
  {
return [data count];
 }

此代码实现.m文件

和.h文件

    {
       NSDictionary *jsonDict;
       IBOutlet UITableView *jsonTable;
       NSArray *data;
       NSURL *url;
    }