2013-06-20 111 views
1

我想解析json中的一些值。我設法得到results.geometry.location的值。如果參數失敗,則服務器返回2值的json。結果是空的[]和狀態「一些錯誤」。iOS 6問題中的JSON解析

url = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false",postalCode]; 

NSData *jsonDataString = [[NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error: nil] dataUsingEncoding:NSUTF8StringEncoding]; 


NSArray* myResults = [NSJSONSerialization JSONObjectWithData:jsonDataString options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error]; 

latLon =[myResults valueForKeyPath:@"results.geometry.location"]; 

generalDict = (NSDictionary *)[latLon objectAtIndex:0]; 

NSLog(@"%@",[generalDict objectForKey:@"lat"]); 

這很混亂。我試過了:

latLon =[myResults valueForKeyPath:@""]; 

generalDict = (NSDictionary *)[latLon objectAtIndex:0]; 

NSLog(@"%@",[generalDict objectForKey:@"status"]); 

但是不起作用。我怎樣才能得到狀態的價值。這是請求無效時的樣子:

{ 
    "results" : [], 
    "status" : "ZERO_RESULTS"  
    } 
+0

不要使用'stringWithContentsOfURL:'。真。它會阻止你的用戶界面(和主線程)。 –

+0

這是我知道的唯一方法:P我希望看到您的解決方案! – BlackM

+0

您可以使用NSURLConnection方法或庫(AFNetworking是最常用的)。有一個[很好的教程](http://www.raywenderlich.com/30445/afnetworking-crash-course)可以幫助你。 –

回答

1

myResults是一個字典,而不是一個數組。我想你想要的東西是這樣的:

NSURL *url = [NSURL urlWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false",postalCode]; 

NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

[NSURLConnection sendAsynchronousRequest:request 
            queue:[NSOperationQueue mainQueue] 
         completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
          NSDictionary *jsonPayload = [NSJSONSerialization JSONObjectWithData:data 
                  options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves 
                   error:nil]; 
          NSString *status = [jsonPayload objectForKey:@"status"]; 
          //Check for error status 
          NSArray *resultsArray = [jsonPayload objectForKey:@"results"]; 
          //Do whatever you want with your results array 
         }];