まず、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..]]
この配列の 1 番目、2 番目、3 番目のオブジェクトが何であるかを推測しなければならないのは、設計上問題があります。array[2]
場所の配列を取得するために暗号的にグラブする必要はありません。
配列は、同等の項目のリストに使用する必要があります (たとえば、場所の配列は完全に理にかなっています)。しかし、この最上位の配列はもう少し怪しげで、3 つの意味的に非常に異なる型の値があり、JSON にはこれら 3 つの項目が何であるかを示すものは何もありません。
この 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..]}
最初の 2 つの値がどうあるべきかわからなかったので、単に と と呼びましたid
がproject
、最初の 2 つの値が何であるかを正確に反映する名前を使用する必要があります。しかし、重要な概念は、場所の配列を名前で参照できる辞書を使用することです。たとえば、ここで提案したように 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