问题描述
- 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"]); }
解决方案
在dictionary之间需要逗号。
{ "speakers" :
[
{
"name":"Value",
"picture": "URL VALUE",
"business":"VALUE",
"desc":"VALUE",
"twitter": "URL VALUE"
} <=== MISSING COMMA HERE
{
...
}
]
}
解决方案二:
既然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"]);
}];
}
} ];
时间: 2025-01-20 14:31:16