objective c parse json from url request

前端 未结 7 1149
醉酒成梦
醉酒成梦 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:29

    Volunteermatch API Objective C

    i am using one common methods for AFNetworking WS Calling. Uses:

    Call WS:

    NSDictionary* param = @{
                            @"action":@"helloWorld",
                            @"query":@"{\"name\":\"john\"}"
                            };
    
    [self requestWithUrlString:@"URL" parmeters:paramDictionary success:^(NSDictionary *response) {
        //code For Success
    } failure:^(NSError *error) {
       // code for WS Responce failure
    }];
    

    Add Two Methods: this two methods are common,u can use these common method in whole project useing NSObject class. also add // define error code like...

    define kDefaultErrorCode 12345

    - (void)requestWithUrlString:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *error))failure {
    
    [self requestWithUrl:stUrl parmeters:parameters success:^(NSDictionary *response) {
        if([[response objectForKey:@"success"] boolValue]) {
            if(success) {
                success(response);
                
            }
        }
        else {
            NSError *error = [NSError errorWithDomain:@"Error" code:kDefaultErrorCode userInfo:@{NSLocalizedDescriptionKey:[response objectForKey:@"message"]}];
            if(failure) {
                failure(error);
            }
        }
    } failure:^(NSError *error) {
        if(failure) {
            failure(error);
        }
    }];}
    

    and // Set Headers in Below Method (if required otherwise remove)

    - (void)requestWithUrl:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *))failure {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
    
    
    [manager.requestSerializer setValue:@"WWSE profile=\"UsernameToken\"" forHTTPHeaderField:@"Authorization"];
    
    
    
    [manager GET:stUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if([responseObject isKindOfClass:[NSDictionary class]]) {
            if(success) {
                success(responseObject);
            }
        }
        else {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            if(success) {
                success(response);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        if(failure) {
            failure(error);
        }
    }];}
    

    For any issues and more Detail please visit..AFNetworking

    0 讨论(0)
  • 2021-02-06 00:30
    //call this method
    -(void)syncWebByGETMethod
    {
          [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        NSString *urlString = [NSString stringWithFormat:@"http://www.yoursite.com"];
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
       [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]                          completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
            {
             if (data)
             {
                 id myJSON;
                 @try {
                     myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                 }
                 @catch (NSException *exception) {
                 }
                 @finally {
                 }
                 jsonArray = (NSArray *)myJSON;
    
                 NSLog(@"mmm %@",jsonArray);
             }
         }];
    }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-06 00:40

    Simple Way to store json-url data in dictionary.

     NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://query.yahooapis.com/v1/public/yql?q=select+%2A+from+weather.forecast+where+woeid%3D1100661&format=json"]];
        NSError *error=nil;
        id response=[NSJSONSerialization JSONObjectWithData:data options:
                     NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
    
        if (error) {
            NSLog(@"%@",[error localizedDescription]);
        } else {
            _query = [response objectForKey:@"query"];
            NSLog(@"%@",_query); 
    

    You can try this, so easy.

    0 讨论(0)
  • 2021-02-06 00:40
    -(void)getWebServic{
    NSURL *url = [NSURL URLWithString:@"----URL----"];
    
    // 2
    NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
                                          dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        NSDictionary *jsonObject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self loadDataFromDictionary:(NSArray*)jsonObject];
        NSLog(@"data: %@",jsonObject);
    
    }];
    
    // 3
    [downloadTask resume]; }
    
    0 讨论(0)
  • 2021-02-06 00:46

    Do this way:

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        // Append the new data to receivedData.
        // receivedData is an instance variable declared elsewhere.
    
        [responseData appendData:data];
    }
    
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSError *e = nil;
    NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
    
    }
    
    0 讨论(0)
提交回复
热议问题