简体   繁体   中英

How to fetch details from NSData

I want to fetch specified data html_instructions from the below URL. I could take all data from this URL .

But I need the specific html_instructions only. How can I split the data?

I used the following code to convert the URL to NSData:

 NSString *url = [NSString      stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=Chennai&destination=Madurai&sensor=false"];
    NSURL *googleRequestURL=[NSURL URLWithString:url];
    dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
    });

Use this as :

    NSData* data = [NSData dataWithContentsOfURL:googleRequestURL];
    if (data == nil) {
        return;
    }
    NSError* error;
    NSMutableDictionary* json = [NSJSONSerialization
                                 JSONObjectWithData:data

                                 options:kNilOptions
                                 error:&error];

    NSLog(@"Json : %@",json);

Hope it helps you.

I parsed the json from the following url and printed the html instructions try copy this code and try: http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false

   NSData *receivedData = Received data from url;
   NSError* error;
   NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:receiveData              options:kNilOptions  error:&error];

           NSArray *allkeys = [parsedJson allKeys];

        for(int i = 0; i < allkeys.count; i++){
            NSLog(@"############################");
            if([[allkeys objectAtIndex:i] isEqualToString:@"routes"]){
                NSArray *arr        = [responseJsonValue objectForKey:@"routes"];
                NSDictionary *dic   = [arr objectAtIndex:0];
                NSLog(@"ALL KEYS FROM ROUTE: %@", [dic allKeys]);
                NSArray *legs = [dic objectForKey:@"legs"];
                  NSLog(@"legs array count %d", legs.count);
                for(int i = 0;  i < legs.count; i++){
                    NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:@"steps"];
                    for (int i = 0; i < stepsArr.count; i++) {
                        NSLog(@"HTML INSTRUCTION %@", [[stepsArr objectAtIndex:i] objectForKey:@"html_instructions"]);
                    }
                }

            }
            NSLog(@"############################");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM