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フィードをNSData
と呼ばれるオブジェクトにロードしたとするとdata
、次のようなことができます。
// 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];