NSJSONSerialization中没有返回

时间:2013-01-09 10:49:17

标签: iphone ios ios5 nsjsonserialization

请你原谅我最后的错误,我可以问这个问题,这是我的第一个。

在阅读本网站上的几个主题之后,like this one首先我会尝试使用describe方法,但它仍然不能全部工作: - (

我的.json文件看起来像这样

{ "speakers" : 
  [
    {
    "name":"Value",
    "picture": "URL VALUE",
    "business":"VALUE",
    "desc":"VALUE",
    "twitter": "URL VALUE"
    }                   
    {
           ...

    }
  ]
}

所以这是我的推理:

我首先有一个词典,其中包含扬声器属性
   这个数组,字段由“name”,“business”中的一些 dictionnaries ,... attr。<登记/> 所以,这是我的obj-C代码:

NSString *URLStr = @"URLofMyJsonFile";

NSURLRequest *JSONRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithString:URLStr ]]];

NSData *JSONData = [NSURLConnection sendSynchronousRequest:JSONRequest returningResponse:nil error:nil];

NSError *parsingError = nil;

NSDictionary *speakerDictionnary = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:&parsingError];

NSArray *speakersArray = [speakerDictionnary objectForKey:@"news"];

for (NSDictionary *oneSpeaker in speakersArray) {
    NSLog(@"The speakers's name is %@", [oneSpeaker objectForKey:@"name"]);
    NSLog(@"The speakers's business is %@", [oneSpeaker objectForKey:@"business"]);
    NSLog(@"The speakers's desc is %@", [oneSpeaker objectForKey:@"desc"]);
}

编辑:我用Dummy重新设置了我的脚本的正确URL

2 个答案:

答案 0 :(得分:3)

您的JSON无效,各个发言人词典之间需要有逗号。

{ "speakers" : 
  [
    {
        "name":"Value",
        "picture": "URL VALUE",
        "business":"VALUE",
        "desc":"VALUE",
        "twitter": "URL VALUE"
    } <=== MISSING COMMA HERE       
    {
       ...
    }
  ]
}

答案 1 :(得分:0)

正如omz提到的,json是错误的。你可以尝试下面的代码:

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.appios.fr/client/takeoff/app/script/jsonSpeaker.json"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *reponse,NSData *data,NSError *error){
        if (!error) {
            NSError *jsonError;
            id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
            NSArray *speakersList = [json objectForKey:@"speakers"];
            [speakersList enumerateObjectsUsingBlock:^(NSDictionary *dict,NSUInteger idx,BOOL *Stop){
                NSLog(@"Name : %@",[dict objectForKey:@"name"]);
            }];
        }

    } ];