objective c parse json from url request

前端 未结 7 1215
醉酒成梦
醉酒成梦 2021-02-06 00:14

I am trying to parse a json string requested from an api located at: http://www.physics.leidenuniv.nl/json/news.php

However, i am having trouble parsing this json. I get

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 00:39

    I would recommend doing it this way:

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.php"]];
    
    __block NSDictionary *json;
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               json = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:nil];
                               NSLog(@"Async JSON: %@", json);
                           }];
    

    Or if for whatever reason (not recommended) you want to run a synchronous request you could do:

    NSData *theData = [NSURLConnection sendSynchronousRequest:request
                          returningResponse:nil
                                      error:nil];
    
    NSDictionary *newJSON = [NSJSONSerialization JSONObjectWithData:theData
                                                            options:0
                                                              error:nil];
    
    NSLog(@"Sync JSON: %@", newJSON);
    

提交回复
热议问题