2 daffodilgirl DaffodilGirl 于 2013.01.10 11:24 提问

NSJSONSerializaton没有返回结果

用了很多方法的都没有返回结果
先看一下代码:

json文件:

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

    }
  ]
}

开始在一个dictionary中保存speaker属性
这个包含一个数组,有一些name,business属性

objective代码:

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

2个回答

redCoral_
redCoral_   2013.01.10 13:49
已采纳

在dictionary之间需要逗号。

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

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

    } ];
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!