你JSON是字典項的數組。所以你可以通過NSJSONSerialization
來檢索完整的數組,然後迭代結果數組中的字典條目。
首先,你原來說你有JSON如下所示:
[{"id":"1","name":"Jiffy Lube","lat":"21.306","lon":"-157.861"},
{"id":"2","name":"Bills Oil","lat":"21.301","lon":"-157.863"},
{"id":"3","name":"Auto Zone","lat":"21.307","lon":"-157.862"}]
因此,如果這是坐在一個文件,「test.json」你已經包含在你的包,你可以加載它像這樣:
// load the data from local file
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
如果你有這樣的一個Web服務器上,你會找回它像這樣:
// load the data from web server
NSURL *url = [NSURL URLWithString:@"http://insert.your.server/and/url/here/test.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// use NSData here
}];
假設ÿ歐加載你的JSON飼料到名爲data
一個NSData
對象,你可能只是這樣做:
// parse the JSON into a NSArray
NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if (error != nil)
{
// handle the error as you want
}
// a few variables to be used as we iterate through the array of results
CLLocationCoordinate2D location; // coordinates of the annotation
NSMutableArray *newAnnotations = [NSMutableArray array]; // an array in which we'll save our annotations temporarily
MKPointAnnotation *newAnnotation; // the pointer to the annotation we're adding
// iterate through the array, adding an annotation to our our array of new annotations
for (NSDictionary *dictionary in array)
{
// retrieve latitude and longitude from the dictionary entry
location.latitude = [dictionary[@"lat"] doubleValue];
location.longitude = [dictionary[@"lon"] doubleValue];
// create the annotation
newAnnotation = [[MKPointAnnotation alloc] init];
newAnnotation.title = dictionary[@"name"];
newAnnotation.coordinate = location;
// add it to our array
//
// incidentally, generally I just add it to the mapview directly, but
// given that you have a didAddAnnotationViews, we'll just build up
// an array and add them all to the map view in one step after we're
// done iterating through the JSON results
[newAnnotations addObject:newAnnotation];
// clean up
[newAnnotation release];
}
// when done, add the annotations
[self.mapView addAnnotations:newAnnotations];
來源
2013-02-10 21:48:14
Rob
你只需要解析JSON字符串NSArrays和NSDictionaries和迭代結果產生MapViewAnnotation實例,並將它們添加到您的MapView 。 如果你需要任何這些「細分」的幫助,我們會很樂意回答他們,或者你可以在這裏檢查他們或用谷歌搜索他們。 祝你好運! – 2013-02-10 21:15:02
謝謝!我仍然得到了Objective-C的竅門,並且誠實地不知道如何正確解析它。這很簡單嗎? – Brandon 2013-02-10 21:17:16
你看過NSJSONSerialization嗎? – 2013-02-10 21:47:24