Reputation: 827
I am trying to parse the following json into my iOS code.
{
"test": [
{
"id": "21",
"lat": "53.343377977116916",
"long": "-6.2587738037109375",
"address": "R138, Dublin, Ireland",
"name": "td56",
"distance": "0.5246239738790947"
},
{
"id": "11",
"lat": "53.343377977116916",
"long": "-6.245641708374023",
"address": "68-130 Pearse Street, Dublin, Ireland",
"name": "test1",
"distance": "0.632357483022306"
}
]
}
I am able to view the full json in my logs with the following code:
NSURL *blogURL = [NSURL URLWithString:@"URLHERE"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *test = [dataDictionary objectForKey:@"test"];
NSLog(@"%@",dataDictionary);
if I change data dictionary to test in the log, I can display after the test root in my json , but if I try setup arrays to view, let's say the ID, the entire app will crash.
Could someone direct me in the right way to, let's say, display all the names in the NSLog
? Each method I've tried has resulted in the application crashing.
Upvotes: 0
Views: 153
Reputation: 362
NSArray *array = [dataDictionary valueForKey:@"test"];
for(int i = 0; i < array.count; i++){
NSLog(@"%@", [array[i] valueForKey:@"name"]);
}
like that u can get NSLog whatever key you want for id
NSLog(@"%@", [array[i] valueForKey:@"id"]);
for lat
NSLog(@"%@", [array[i] valueForKey:@"lat"]);
and so on..... Happy coding
Upvotes: 2
Reputation: 45490
Test is an array:
NSArray *test = [dataDictionary objectForKey:@"test"];
NSLog(@"test =%@", test);
for(NSDictionary *coordinates in test){
NSLog(@"id = %@", coordinates[@"id"]);
NSLog(@"lat = %@", coordinates[@"lat"]);
NSLog(@"long = %@", coordinates[@"long"]);
}
Upvotes: 2