简体   繁体   English

json iOS解析错误

[英]json iOS parsing error

I am trying to parse the following json into my iOS code. 我正在尝试将以下json解析为我的iOS代码。

{
    "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: 我可以使用以下代码查看日志中的完整json:

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. 如果我更改数据字典以在日志中进行测试,则可以在json的测试根目录之后显示,但是如果我尝试查看安装数组以查看ID,则整个应用程序将崩溃。

Could someone direct me in the right way to, let's say, display all the names in the NSLog ? 有人可以用正确的方式指导我,例如在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任何您想要的ID密钥

NSLog(@"%@", [array[i] valueForKey:@"id"]);

for lat 对于拉特

NSLog(@"%@", [array[i] valueForKey:@"lat"]);

and so on..... Happy coding 等等.....快乐的编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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