我从我的服务器获取并得到有效的响应:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
//[_responseData appendData:data];
NSString *responseBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseBody);
if(data != NULL)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
NSError *error = nil;
//NSMutableArray *jsonArray = [[CJSONDeserializer deserializer] deserializeAsArray:[responseBody dataUsingEncoding:NSUTF8StringEncoding] error:&error];
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if (error)
{
NSLog(@"JSONObjectWithData error: %@", error);
[delegate onErrorGetArrayFromServer];
}
else
[self parseJSON:jsonArray];
});
}
else
{
if([delegate respondsToSelector:@selector(onErrorGetArrayFromServer)])
{
[delegate onErrorGetArrayFromServer];
}
}
}
响应如下:
[{
"id": "37",
"id_estado": "1",
"id_categoria": "1",
"nombre": "fer",
"email": "[email protected] /cdn-cgi/l/email-protection",
"fecha": "2014-07-16 11:25:00",
"observaciones": "as dasd asdasd sasd",
"latitud": "37.619636",
"longitud": "-4.318449",
"foto": "images\/default.jpg"
},
{
"id": "36",
"id_estado": "1",
"id_categoria": "6",
"nombre": "Fernando",
"email": "",
"fecha": "2014-07-16 10:32:45",
"observaciones": "que",
"latitud": "37.6178690439634",
"longitud": "-4.3238141387701",
"foto": "images\/default.jpg"
}
]
###它向我抛出错误:###
JSONObjectWithData error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x9e0f610 {NSDebugDescription=Invalid value around character 0.}
我尝试过其他图书馆(CJSON)它给我带来了错误:
JSONObjectWithData error: Error Domain=kJSONScannerErrorDomain Code=-202 "Could not scan array. Could not scan a value." UserInfo=0xa15c0e0 {snippet=!HERE>![{"id":"37","id_esta, location=0, NSLocalizedDescription=Could not scan array. Could not scan a value., character=0, line=0}
我的服务器是 REST 服务器,对于我的 Android 应用程序运行良好。
SOLVED
感谢@Himanshu Joshi:
为什么要解析 didReceiveData: 中的数据?那里的数据没有完全下载,你必须在那里附加数据。解析connectionDidFinishLoading:委托方法中的数据 –
我解析了数据connectionDidFinishLoading:
一切都很顺利。