字符串到JSON数组无法识别的选择器错误

时间:2012-07-28 02:42:56

标签: ios nsarray nsjsonserialization

我正在尝试将一些JSON解析为NSArray但是我收到以下错误:

[__NSCFDictionary length]: unrecognized selector sent to instance 0x6d7a160

抛出此错误的代码区域是:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {


NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSError* error;
NSLog(responseString);
NSArray *jsonArray = [NSJSONSerialization 
          JSONObjectWithData:responseData
          options:NSJSONReadingMutableContainers
          error:&error];
parties2=jsonArray;
NSLog([parties2 objectAtIndex:0]); //Exception thrown

[tableView reloadData];

}

派对2先前被定义为:

parties2=[NSArray arrayWithObjects:nil];

我的ResponseString看起来像

[{"Name":"party 1.1","GreekName":"FoA 1","GreekID":325,"schoolName":"FoA University","schoolID":10,"numberAttending":0,"maxNumberAttending":1000,"price":15.0},{"Name":"party 1.2","GreekName":"FoA 1","GreekID":325,"schoolName":"FoA University","schoolID":10,"numberAttending":0,"maxNumberAttending":300,"price":20.0},{"Name":"party 1.3","GreekName":"FoA 1","GreekID":325,"schoolName":"FoA University","schoolID":10,"numberAttending":0,"maxNumberAttending":5000,"price":25.0},{"Name":"party 2.1","GreekName":"FoA 2","GreekID":326,"schoolName":"FoA University","schoolID":10,"numberAttending":0,"maxNumberAttending":500,"price":25.0},{"Name":"party 2.2","GreekName":"FoA 2","GreekID":326,"schoolName":"FoA University","schoolID":10,"numberAttending":0,"maxNumberAttending":300,"price":30.0},{"Name":"party 3.1","GreekName":"FoA 3","GreekID":327,"schoolName":"FoA University","schoolID":10,"numberAttending":0,"maxNumberAttending":0,"price":50.0},{"Name":"party 5.1","GreekName":"FoA 5 ","GreekID":329,"schoolName":"FoA University","schoolID":10,"numberAttending":0,"maxNumberAttending":300,"price":15.75}]

这是我与ObjC的第一次合作,我来自.Net C#背景,所以很可能我错过了一件非常简单的事情。

谢谢:)

1 个答案:

答案 0 :(得分:0)

您的JSON解析是正确的。由于NSLog()语句中的语法错误而引发错误。

NSLog()将NSString作为参数,但是您正在尝试传递NSDictionary(即NSArray的第一个元素),这会导致错误。

解决方法是使用NSString格式字符串将NSDictionary对象转换为字符串,如下所示:

NSLog(@"%@",[parties2 objectAtIndex:0]);