简体   繁体   中英

json iOS parsing error

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.

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"]);
}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM