【发布时间】:2011-08-28 21:46:00
【问题描述】:
我最近求助于从 Google Maps API 获取我的邮政编码数据。在这个问题的结尾,我包含了我从 Google 收到的 JSON 响应字符串的一个大的 sn-p。
在我的代码深处,我得到了响应,并使用来自 Jonathan Wight 的 TouchJSON 库对其进行解析。这是我的代码
NSStringEncoding encoding;
// Fetch data from web service.
NSString *jsonString = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:nil];
// Process JSON data returned from web service.
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil];
if (jsonString == nil)
{
// bah
} else if (![self isCancelled]) {// Check to see if we have been cancelled.
if (dictionary) {
NSArray* results = [dictionary objectForKey:@"results"];
NSDictionary* types = [results objectAtIndex:1];
NSArray* address_components = [types objectForKey:@"address_components"];
NSDictionary* postcodes = [address_components objectAtIndex:0];
NSString* postcode = [postcodes objectForKey:@"long_name"];
// do stuff with the postcode
}
//
}
注意我是如何通过使用 NSArray 中的特定偏移量来获取类型字典和邮政编码字典的。我的问题真的是这样,
如何解析 JSON 字符串(最好使用 TouchJSON),而无需对这些数组偏移量进行硬编码?
让我感到震惊的是,Google 地图响应字符串可能会发生变化,而我的硬编码方法将在那时停止工作。有没有人使用过他们愿意在这里分享的类似但更强大的方法?
...Google Maps API 示例响应字符串...“目标”邮政编码以粗体突出显示
{ “状态”:“OK”,“结果”:[ { “类型”:[“街道地址”], "formatted_address": "9 Clarendon Pl, Leamington Spa, Warwickshire CV32 5, UK", “地址组件”:[{ "long_name": "9", "short_name": "9", “类型”:[“街道号码”] }, { "long_name": "克拉伦登 Pl", "short_name": "A452", “类型”:[“路线”] }, { "long_name": "利明顿水疗中心", "short_name": "利明顿水疗中心", “类型”:[“地方”,“政治”] }, { "long_name": "沃里克", "short_name": "沃里克", “类型”:[“administrative_area_level_3”,“政治”] }, { "long_name": "沃里克郡", "short_name": "Warks", “类型”:[“administrative_area_level_2”,“政治”] }, { "long_name": "英格兰", "short_name": "英格兰", “类型”:[“administrative_area_level_1”,“政治”] }, { "long_name": "英国", "short_name": "GB", “类型”:[“国家”,“政治”] }, { "long_name": "CV32 5", "short_name": "CV32 5", “类型”:[“邮政编码前缀”,“邮政编码”] }], “几何学”: { “地点”: { “纬度”:52.2919849, “液化天然气”:-1.5399505 }, "location_type": "RANGE_INTERPOLATED", “视口”:{ “西南”:{ “纬度”:52.2888374, “液化天然气”:-1.5431216 }, “东北”:{ “纬度”:52.2951326, “液化天然气”:-1.5368264 } }, “界限”:{ “西南”:{ “纬度”:52.2918320, “液化天然气”:-1.5399760 }, “东北”:{ “纬度”:52.2921380, “液化天然气”:-1.5399720 } } } }, { “类型”:[“邮政编码”], "formatted_address": "Leamington Spa, Warwickshire CV32 5LD, UK", “地址组件”:[{ "long_name": "CV32 5LD", "short_name": "CV32 5LD", “类型”:[“邮政编码”] }, { "long_name": "利明顿水疗中心", "short_name": "利明顿水疗中心", “类型”:[“地方”,“政治”] }, ......... 更多 JSON 跟随
【问题讨论】:
标签: iphone json google-maps