Update:我刚刚使用以下命令测试了从服务器返回的 JSON 格式JSONlint没关系。
我在 AFNetworking 调用返回 JSON 数据的 php 脚本时遇到 NSJSONSerialization 异常。我在这里查看了具有相同问题的其他问题并尝试了这些解决方案,但仍然收到错误。
它在这条线上崩溃:
NSError *e = nil;
NSMutableArray *jsonArray =
[NSJSONSerialization JSONObjectWithData: jsonData
options: NSJSONReadingMutableContainers
error: &e];
错误日志:
2012-03-19 18:10:41.291 图像上传器[3538:207]*由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSCFArray bytes]:无法识别的选择器发送到实例 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 如下所示:
(
{
索引=101;
路径=“binky-0a96f9aab5267c8.jpg”;
用户=宾基;
},
{
索引=102;
路径=“binky-9cf844252c28553.jpg”;
用户=宾基;
},
{
索引=103;
路径=“binky-d6c749d25d33015.jpg”;
用户=宾基;
} )
最后,我做了一个测试以确保我有有效的 JSON 数据:
if ([NSJSONSerialization isValidJSONObject: jsonData]){
NSLog(@"Good JSON \n");
}
所以我无法理解我的错误根源在哪里。帮助不大?
// AF网络操作+区块
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];
}];