使用我的ios应用程序我向google地方api发出请求,我得到这样的回复:
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "Rome",
"short_name" : "Rome",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Rome",
"short_name" : "Rome",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Metropolitan City of Rome",
"short_name" : "RM",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Lazio",
"short_name" : "Lazio",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Italy",
"short_name" : "IT",
"types" : [ "country", "political" ]
}
],
"adr_address" : "\u003cspan class=\"locality\"\u003eRome\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eItaly\u003c/span\u003e",
"formatted_address" : "Rome, Italy",
"geometry" : {
"location" : {
"lat" : 41.9027835,
"lng" : 12.4963655
},
"viewport" : {
"northeast" : {
"lat" : 42.0505462,
"lng" : 12.7302888
},
"southwest" : {
"lat" : 41.769596,
"lng" : 12.341707
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "c201ff6d6339dac3b34184b3972b232aa097ff8a",
"name" : "Rome",
"place_id" : "ChIJu46S-ZZhLxMROG5lkwZ3D7k",
"reference" : "CnRoAAAAUe_x9QmJ7kGAAAoyOwa_6vGISj0hy4mvqTJNjNl9TrXqaowyKQCEQov70GTyVidSdNd9wy0MG9UWffjSmi58YG7R3j2Fr9_RoKJCjKgcxwijojmVgFNf5p-8Ja1E53D_YnzW8R0lgtY1xMmOZvxzEBIQ1ruuMP92aFYZs-EJd0McJRoUOaLCDU0K4Dh9nag9wouUAsHqC3g",
"scope" : "GOOGLE",
"types" : [ "locality", "political" ],
"url" : "https://maps.google.com/maps/place?q=Rome,+Italy&ftid=0x132f6196f9928ebb:0xb90f770693656e38",
"vicinity" : "Rome"
},
"status" : "OK"
}
我使用以下代码获取address_components:
NSDictionary *ResultDictionary = [body objectFromJSONString];
for (NSDictionary *q in [[ResultDictionary valueForKey:@"result"]valueForKey:@"address_components"]) {
NSArray *type=[q valueForKey:@"types"];
NSArray *long_name=[q valueForKey:@"long_name"];
NSArray *short_name=[q valueForKey:@"short_name"];
}
使用相同的逻辑,我无法获得几何对象下的视口和位置值,这会导致崩溃,因为该键不存在:
for (NSDictionary *q in [[ResultDictionary valueForKey:@"result"]valueForKey:@"geometry"] ) {
NSArray *location=[q valueForKey:@"location"];
}
似乎json decode只提取了一个字符串而不是几何对象的nsDictionary,这有什么不对?
答案 0 :(得分:1)
在您的代码中添加此内容,并根据您的要求从JSON
获取您的价值
NSMutableDictionary *NewDict=[[[ResultDictionary valueForKey:@"result"]valueForKey:@"geometry"] objectForKey:@"location"];
NSString *lat=[NewDict objectForKey:@"lat"];
NSString *lng =[NewDict objectForKey:@"lng"];
我希望这段代码对你有用。
答案 1 :(得分:0)
你的"几何"节点包含两个词典,其中只有一个具有" location"节点,这就是它崩溃的原因(你要求他们两个都回复键#34的位置;位置"不先检查是否有一个)。提供的答案将解决您的问题,直接钻到"位置"没有迭代的部分,你就会得到你的价值观。
考虑到你已经得到了答案,你可能会通过使用更高级别的JSON库来节省一些麻烦,例如:http://www.jsonmodel.com/