2013-10-18 61 views
-4

我试图解析这个看起来像我写得很好的JSON,但NSJSONSerialization不认为相同的AFAIK,因为它返回NSArrayNSJSONSerialization不解析这个JSON

这是我的代码:

NSData* gamesData = [NSData dataWithContentsOfURL: 
         [NSURL URLWithString:@"http://s42sport.com/polarice/json/games.json"] 
         ]; 

    NSDictionary* json = nil; 
    if (gamesData) { 
     json = [NSJSONSerialization 
       JSONObjectWithData:gamesData 
       options:kNilOptions 
       error:nil]; 
     NSLog(@"%d",json.count); 
    } 

的问题是,

有什么不对的JSON?为什么NSSerialization不会返回给我NSDictionary?

编辑:是的,我刚刚了解了vs {...}。谢谢。

+3

JSON是一个数组。除了你期望它是一本字典以外没有什么不对。 – rmaddy

+0

查看我的代码suerly为你工作... – Jitendra

+1

看起来像你没有花费很多精力在寻找甚至基本的JSON语法。 – hawk

回答

2

解析您的json通过这种方式。

NSURL * url=[NSURL URLWithString:@"http://s42sport.com/polarice/json/games.json"]; 

NSData * data=[NSData dataWithContentsOfURL:url]; 

NSError * error; 

NSMutableDictionary * json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; 

NSLog(@"%@",json); 

NSArray * array1=[json valueForKey:@"c"]; 

NSLog(@"%@",array1); 

试试看看这个代码。这一定会为你工作。

+0

是的,这工作,因为选项:NSJSONReadingMutableLeaves? –

+0

快乐编码..... – Jitendra

+0

我可以问,代码有什么区别?你现在让它返回一个NSmutableDictionary。我认为它会返回一个NSMutableArray –

0

您列出的JSON文件是一个数组(它以一个方括号开头和结尾),因此Objective-C使用NSArray根对象反映了这一点。

+0

是的,这就是我刚学的东西。谢谢。 –

1

NSDictionnary应该用于对象,而NSArray的是使用了JSON阵列

NSArray* json = nil; 
if (gamesData) { 
    json = [NSJSONSerialization 
      JSONObjectWithData:gamesData 
      options:kNilOptions 
      error:nil]; 
    NSLog(@"%d",json.count); 
}