首先,您首先解析您的 JSON:
NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSAssert(array, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);
其次,您可以从该顶级数组中获取位置数组,为该数组中的每个位置字典创建注释,并将其添加到您的地图中:
// the array of locations is the third object in the top-level array
NSArray *locations = array[2];
// now iterate through this array of locations
for (NSDictionary *location in locations)
{
// grab the latitude and longitude strings
NSString *latitudeString = location[@"lat"];
NSAssert(latitudeString, @"No latitude");
NSString *longitudeString = location[@"lng"];
NSAssert(longitudeString, @"No longitude");
// create the annotation and add it to the map
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = CLLocationCoordinate2DMake([latitudeString doubleValue], [longitudeString doubleValue]);
annotation.title = location[@"name"];
annotation.subtitle = location[@"address"];
[self.mapView addAnnotation:annotation];
}
话虽如此,我必须说我不关心 JSON 格式:
["VALUE","proyect",[{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]]
对于我们来说,必须猜测这个数组中的第一个、第二个和第三个对象是什么,这是一个值得怀疑的设计。我们不必神秘地抓取array[2]
来获取位置数组。
数组应该用于等价项目的列表(例如,位置数组非常有意义)。但是这个顶级数组有点可疑,具有三种语义上非常不同的值类型,JSON 中没有任何内容可以指示这三个项是什么。
如果您坚持使用这种 JSON 格式,那么,很好,上面的代码应该可以完成这项工作。但希望您可以将此处的顶级结构更改为字典,而不是数组,您可以在其中使用键名来标识此顶级字典中的各种项目,例如:
{"id" : "VALUE", "project" : "proyect", "locations" : [{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]}
我不知道前两个值应该是什么,所以我只称它们为id
and project
,但您显然应该使用真正反映前两个值的名称。但关键概念是使用字典,您可以在其中按名称引用位置数组。例如,如果 JSON 像我在这里建议的那样更改,则解析它的代码将变为:
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSAssert(dictionary, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);
NSArray *locations = dictionary[@"locations"];
此外,作为一种风格观察,许多人通常会将纬度和经度值表示为数字(不带引号),并将NSJSONSerialization
它们解析为NSNumber
对象而不是NSString
对象。但这取决于你。