【发布时间】:2013-06-16 23:25:57
【问题描述】:
-(void) conn:(NSString *)method{
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
__block NSDictionary *resultBlock = nil;
dispatch_sync(concurrentQueue, ^{
/* Download the json here */
//Create webservice address
NSString *webService = [_baseURL stringByAppendingString:_webService];
//NSLog(@"%@", webService);
//Create error object
NSError *downloadError = nil;
//Create the request
NSMutableURLRequest *req = [self initRequest:webService method:method];
if(req != nil){
//Request the json data from the server
NSData *jsonData = [NSURLConnection
sendSynchronousRequest:req
returningResponse:nil
error:&downloadError];
if(downloadError!=nil){
NSLog(@"DOWNLOAD ERROR %@", downloadError);
}
NSError *error = nil;
id jsonObject = nil;
if(jsonData !=nil){
/* Now try to deserialize the JSON object into a dictionary */
jsonObject = [NSJSONSerialization
JSONObjectWithData:jsonData
options:kNilOptions
error: &error];
}
//Handel the deserialized object data
if (jsonObject != nil && error == nil){
NSLog(@"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]){
resultBlock = (NSDictionary *)jsonObject;
//NSLog(@"Deserialized JSON Dictionary = %@", resultBlock);
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"Deserialized JSON Array = %@", deserializedArray);
} else {
/* Some other object was returned. We don't know how to deal
with this situation, as the deserializer returns only dictionaries
or arrays */
}
}
else if (error != nil){
NSLog(@"An error happened while deserializing the JSON data. %@", error);
}else{
NSLog(@"No data could get downloaded from the URL.");
//[self conn:method];
}
}
});
dispatch_sync(dispatch_get_main_queue(), ^{
/* Check if the resultBlock is not nil*/
if(resultBlock != nil){
/*Set the value of result. This will notify the observer*/
[self setResult:resultBlock];
}
});
});
}
为什么会出现以下错误?
反序列化 JSON 数据时出错。错误 Domain=NSCocoaErrorDomain Code=3840 "无法执行该操作 完全的。 (Cocoa 错误 3840。)”(JSON 文本不是以数组开头或 允许未设置片段的对象和选项。) UserInfo=0x20839f80 {NSDebugDescription=JSON 文本不是以数组或对象开头并且 允许未设置片段的选项。}
当我把它改成
/* Now try to deserialize the JSON object into a dictionary */
jsonObject = [NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error: &error];
}
我收到以下错误:
反序列化 JSON 数据时出错。错误 Domain=NSCocoaErrorDomain Code=3840 "无法执行该操作 完全的。 (Cocoa 错误 3840。)”(字符 0 周围的值无效。) UserInfo=0x20888760 {NSDebugDescription=字符周围的值无效 0.}
我将连接从 LTE 更改为 wifi,现在我得到了 504 错误和 NSLog(@"无法从 URL 下载数据。");
【问题讨论】:
-
看来你的JSON是无效的,你可以使用在线工具来验证它例如this one
-
我验证了json,很好
-
你能在其他 JSON 上测试你的代码吗?
-
我已经写了一个 JSON 解析器。我只需要尝试将 JSON 对象反序列化为字典,但我收到 504 错误,这意味着服务器可能有问题。
-
虽然我这样做很麻烦,但我必须给你 +1 以实际检查错误值。
标签: objective-c json nsjsonserialization