我正在尝试从经度和纬度检索邮政编码。因此,我使用google API。
这是我的请求。
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.04166373133121,5.580196380615234&sensor=true
当您在浏览器中输入这段代码时,您将看到整个JSON。这只是其中的一部分。
JSON文件
{
"results": [
{
"address_components": [
{
"long_name": "2",
"short_name": "2",
"types": [
"street_number"
]
},
{
"long_name": "Hermisweg",
"short_name": "Hermisweg",
"types": [
"route"
]
},
{
"long_name": "Opglabbeek",
"short_name": "Opglabbeek",
"types": [
"locality",
"political"
]
},
{
"long_name": "Limburg",
"short_name": "LI",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Vlaams Gewest",
"short_name": "Vlaams Gewest",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "België",
"short_name": "BE",
"types": [
"country",
"political"
]
},
{
"long_name": "3660",
"short_name": "3660",
"types": [
"postal_code"
]
}
]
}
]
}我现在的问题是如何从这个JSON中获取邮政编码?在这个例子中,我想要3660作为输出。
有谁有主意吗?
发布于 2013-02-27 18:57:37
在connectionDidFinishLoading中试试这个。
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *thexml=[[[NSString alloc] initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding] autorelease];
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[thexml dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
NSLog(@"JsonError: %@",jsonError);
NSArray *result = [(NSDictionary*)allValues objectForKey:@"results"];
for(int i=0;i<[result count];i++)
{
NSDictionary *values = (NSDictionary*)[result objectAtIndex:i];
NSArray *component = [(NSDictionary*)values objectForKey:@"address_components"];
for(int j=0;j<[component count];j++)
{
NSDictionary *parts = (NSDictionary*)[component objectAtIndex:j];
if([[parts objectForKey:@"types"] containsObject:@"postal_code"])
{
NSLog(@"Postal Code : %@ ",[parts objectForKey:@"long_name"]);
break;
}
}
}
}发布于 2013-02-27 18:34:28
你想要关键字是"long_name“的"3600”...所以你基本上想要"long_name“。
试试这个:-
假设您在resultDict中获得了所有结果。
NSString *long_name = [[[[[resultDict objectForKey:@"results"] objectAtIndex:0] objectForKey:@"address_components"] objectAtIndex:0] objectForKey:@"long_name"];
NSLog(@"long_name is %@",long_name);注意:-你必须将0替换为for循环的变量(例如"i"),把你在结果字典中得到的数组中的元素数放在那里。
发布于 2013-02-27 18:26:45
将这个JSON映射到一个NSDictionary类。从这里您可以访问address_components数组。
使用数组objectAtIndex获取所需的值。
如果您需要全面的解决方案,请使用github中提供的抽象KVC包装器类
它们直接将JSON映射到模型类。
一旦映射完成,您就可以通过指定:这些类的object.property来访问这些类。
https://stackoverflow.com/questions/15109564
复制相似问题