更新:我刚刚使用JSONlint测试了从服务器返回的 JSON 格式,这很好。
我在 AFNetworking 调用返回 JSON 数据的 php 脚本时遇到 NSJSONSerialization 异常。我在这里查看了具有相同问题的其他问题,并尝试了这些解决方案,但仍然出现错误。
它在这条线上崩溃:
NSError *e = nil;
NSMutableArray *jsonArray =
[NSJSONSerialization JSONObjectWithData: jsonData
options: NSJSONReadingMutableContainers
error: &e];
错误日志:
2012-03-19 18:10:41.291 imageUploader[3538:207] *由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSCFArray 字节]:无法识别的选择器发送到实例 0x6867430”
当我通过浏览器调用 php 脚本时,我的 JSON 数据如下所示:
[{"user":"binky","path":"binky-0a96f9aab5267c8.jpg","index":"101"},{"user":"binky","path":"binky-9cf844252c28553.jpg ","index":"102"},{"user":"binky","path":"binky-d6c749d25d33015.jpg","index":"103"}]
数据的 NSLog 如下所示:
( { index = 101; path = "binky-0a96f9aab5267c8.jpg"; user = binky; }, { index = 102; path = "binky-9cf844252c28553.jpg"; user = binky; }, { index = 103; path = “binky-d6c749d25d33015.jpg”;用户 = binky;})
最后,我做一个测试以确保我有有效的 JSON 数据:
if ([NSJSONSerialization isValidJSONObject: jsonData]){
NSLog(@"Good JSON \n");
}
所以我不明白我的错误的根源在哪里。一点帮助?
// AFNetworking 操作 + 块
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:myRequest
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id jsonData) {
NSLog(@"Success JSON data:\n %@ \n", jsonData); //log data
if ([NSJSONSerialization isValidJSONObject: jsonData]){
NSLog(@"Good JSON \n");
}
NSError *e = nil;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
[self.navigationController popToRootViewControllerAnimated:YES];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Error: %@", error);
[self.navigationController popToRootViewControllerAnimated:YES];
}];