首页 文章

在反序列化JSON数据时发生错误

提问于
浏览
1
-(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数据时发生错误 . Error Domain = NSCocoaErrorDomain Code = 3840“操作无法完成 . (Cocoa error 3840.)”(JSON文本没有以数组或对象开头,并且选项允许未设置片段 . )UserInfo = 0x20839f80 {NSDebugDescription = JSON text没有从数组或对象和选项开始,以允许未设置片段 . }

当我改为

/* Now try to deserialize the JSON object into a dictionary */
                jsonObject = [NSJSONSerialization
                                 JSONObjectWithData:jsonData
                                 options:NSJSONReadingAllowFragments
                                 error: &error];
            }

我收到以下错误:

反序列化JSON数据时发生错误 . 错误域= NSCocoaErrorDomain代码= 3840“操作无法完成 . (Cocoa错误3840 . )”(字符0周围的值无效 . )UserInfo = 0x20888760

我改变了从LTE到wifi的连接,现在我得到504错误和NSLog(@“没有数据可以从URL下载 . ”);

1 回答

  • 1

    您应该首先在代码中解决这些问题:

    • 正确检查方法中的错误,这些方法提供指向 NSError 对象的引用的指针作为最后一个参数,例如: - (BOOL) doSomething:(NSError**)error-(NSData*) doSomething:(NSError**)error

    为了正确测试错误,您必须仅检查方法的返回值 . 这些方法用"special return value"表示错误情况 . 例如,它们返回 NOnil - 如文档中一直指定的那样 . 只有在方法指示错误之后,提供的错误参数才包含有意义的值 - 也就是说,它指向由方法创建的 NSError 对象 . 请注意,当方法成功时,此参数也可能变为无NULL,在这种情况下,该参数没有"meaning" .

    • Web服务通常可以提供所请求资源的多种格式 . 如果您没有指定服务器对资源进行编码的格式,则会获得默认格式 - 不一定是JSON .

    为了明确所需的资源格式,请设置相应的"Accept"标头 . 例如,如果您希望使用JSON格式,则可以在请求中设置 Headers : "Accept: application/json" .

    • Web服务可能有理由不响应您请求的资源 . 为了确保获得您请求的响应,您需要检查状态代码和MIME类型的响应,以确保您实际收到了JSON响应 .

    • 看来,您对如何使用调度功能有点不确定 . 如果您使用同步方便的方法 sendSynchronousRequest:... 您当然只需要将其包装在一个dispatch_async函数中 . 如果您想在主线程上设置结果,您当然希望使用 dispatch_async ,而不是dispatch_sync .

    但是,如果您使用 sendAsynchronousRequest:... ,那将是一个改进 . 并且只有你在异步模式下使用 NSURLConnection 并实现 NSURLConnection 委托方法 - 我强烈建议 - 它实际上会变得很棒;)

    所以,我认为,一旦你修改了你的代码,你就可以自己回答原始问题,或者从服务器得到更好的错误响应,或者错误神奇地消失了;)

相关问题