试图用json捕获数据,它返回null

时间:2014-11-07 12:42:22

标签: ios json xcode5

我是Xcode,iOS和json的新手,所以我正在尝试从我的服务器获取数据但是当我调用该操作时它返回null。请帮帮我吗?

以下是代码:

- (IBAction)buscardados:(id)sender {

    NSURL *local = [NSURL URLWithString:panhacaminho];

    NSData *datas = [NSData dataWithContentsOfURL:local];

    json=[NSJSONSerialization JSONObjectWithData: datas options:kNilOptions error:nil];

    dados=[[NSMutableArray alloc]init];
    for (int i=0; i<json.count; i++)
    {
        entrantsArray = [[[json objectForKey:@"ID"] allValues] objectAtIndex:i];


    }
    NSLog(@" Identificacao: %@", entrantsArray);

}

Json中的数据:

{ “aviao”:[{ “ID”: “1”, “NOME”: “ART580”, “LOGO”:NULL, “NOMECOMPAINHA”: “TACV”, “CAPACIDADE”: “250”,“DATE_LOG “:”2013-12-10 17:02:34“,”vooses“:[{”ID“:”1“,”CODIGO“:”V534PS“,”ID_ROTA“:”1“,”ID_AVIAO“:” 1" , “AEROPORTOPARTIDA”: “1”, “AEROPORTOCHEGADA”: “2”, “DATAPARTIDA”: “2013年8月8日”, “DATACHEGADA”: “2013年8月9日”, “HORAPARTIDA”:“23: 45:00“,”HORACHEGADA“:”02:20:00“,”TIPOVOO“:”Nacional“,”ESTADO“:”0“,”DATE_LOG“:”2013-12-10 17:02:47“}

我想在变量中获得这些atributs

2 个答案:

答案 0 :(得分:1)

您需要通过调用NSLog(@“%@”,json)来确定您是否收到了任何数据以及数据的结构。

您需要认真学习NSDictionary,NSArray等基础知识,因为您编写的代码表明您对此一无所知。 Xcode包含您需要的所有类的文档。

答案 1 :(得分:0)

这取决于您从服务器获得的响应。如果你有类似的东西:

在这里编辑您的答案信息:

{"aviao": [{"ID":"1","NOME":"ART580","LOGO":null,"NOMECOMPAINHA":"TACV","CAPACIDA‌​DE":"250","DATE_LOG":"2013-12-10 17:02:34",...

你可以尝试这个:

NSError *e = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];

if (!json) {
   NSLog(@"Error parsing JSON: %@", e);
} else {
   NSArray *arrayTemp = json[@"aviao"]
   for(NSDictionary *item in arrayTemp) {
      NSLog(@"Item: %@", item);
      //or, to check some values....
      NSLog(@"ID:%@  NOME:%@ LOGO:%@",item[@"ID"],item[@"NOME"],item[@"LOGO"]);
   }
}