将字典键值转换为NSNumber

时间:2013-09-04 10:11:02

标签: objective-c json nsdictionary

我刚刚成功完成了我的第一个JSON请求并反序列化了信息,现在我需要做的就是知道如何从我的字典中收集一些值。这是请求的样子:

@implementation ViewController {
    GMSMapView *mapView_;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Make the URL connection in order to download JSON/XML data.
    NSString *urlAsString = @"weburlgoeshere...";
    NSURL *url = [NSURL URLWithString:urlAsString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    // Error and success message handling.
    [NSURLConnection
    sendAsynchronousRequest:urlRequest
    queue:queue
     completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
         if([data length] > 0 &&
            error == nil){
             NSData *jsonData = [NSData dataWithContentsOfURL:url];

             if (jsonData != nil){
                 NSError *error = nil;

                 NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                 if(error == nil)
                 NSLog(@"%@", [result valueForKey:@"merchants"]);
             }

         }
         else if ([data length] == 0 &&
         error == nil){
         NSLog(@"Nothing was downloaded");

         }
         else if (error != nil){
         NSLog(@"Error happened = %@", error);

         }


     }];

}

这是注销到控制台的内容:

branches =         (
                        {
                city = "......";
                country = "United States";
                countryIsoCode = USA;
                distanceInKms = "8.31";
                distanceInMiles = "5.16";
                id = 7952205;
                latitude = ".......";
                longitude = "........";
                name = ".......";
                state = ......;
                stateIsoCode = .....;
                street = ".........";
                telephone = "";
            }
        );
        id = 174535;
        logoUrl = ".......";
        name = ".......";

所以我将所有这些值存储在我称为“result”的NSDictionary中,我想知道如何收集和存储纬度和经度的 SPECIFIC 键值在NSNumber中。我想我可能需要用块来快速枚举大部分这些,然后相应地处理。这里的目的是使用这些值并将它们显示在地图上。任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过这种方式访问​​密钥的必需值。

NSArray * array = [dic objectForKey:@"branches"];
NSDictionary *furtherNames = array[0];
NSNumber *latitude = [NSNumber numberWithFloat:[[furtherNames objectForKey:@"latitude"] floatValue]];
NSNumber *longitude = [NSNumber numberWithFloat:[[furtherNames objectForKey:@"longitude"] floatValue]];

您需要注意的是()=>对象数组,{} =>字典。因此,相应地遍历它们。

希望这有帮助。