0

我正在尝试将一些 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# 背景,所以我很可能错过了一个非常简单的东西。

谢谢 :)

4

1 回答 1

0

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

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

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

NSLog(@"%@",[parties2 objectAtIndex:0]);
于 2012-07-28T17:10:34.900 回答