【问题标题】:Invalid value around character 0, NSJSONSerialization字符 0 周围的值无效,NSJSONSerialization
【发布时间】:2014-09-08 05:26:51
【问题描述】:

我从我的服务器获取并得到有效响应:

- (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": "asd@gmail.com",
        "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 应用运行良好。


已解决

感谢@Himanshu Joshi:

为什么要解析 didReceiveData: 中的数据?数据没有完全下载到那里,你必须在那里附加数据。解析connectionDidFinishLoading中的数据:委托方法——

我解析了connectionDidFinishLoading:中的数据,一切正常。

【问题讨论】:

  • 在开头的“[”之前看起来像是一些垃圾数据。 NSLog 记录您收到的 NSData 并向我们展示前十几个字节。
  • [{"id":"37","id_estado":"1","id_categoria":...
  • 为什么要解析didReceiveData:中的数据?数据没有完全下载到那里,你必须在那里附加数据。解析connectionDidFinishLoading:委托方法中的数据
  • 我爱你,我为这个愚蠢的错误浪费了我的早上:D
  • @ƒernandoValle:您记录的是字符。不是字节。我可以看看字节是否错误。我看不出字符有没有错。

标签: ios ios7 nsjsonserialization


【解决方案1】:

我遇到了同样的问题,但这是因为我的初始 URL 不正确。

在解析 JSON 之前需要检查响应。它可能会告诉你它没有找到。

此时数据实际上可以包含一个 404 HTML 页面。

我使用这些方法来调试这个,以及更简单的方法来处理网络请求:

// Asynchronous fetch the JSON and call the block when done
NSURLSessionDataTask *downloadTask =
[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) 
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;

    if ([httpResponse statusCode]!=200) 
    {
        // log [response  description]
        // log [NSString stringWithUTF8String:[data bytes]] 
        return;
    }

    NSDictionary* jsonDic =     
        [NSJSONSerialization JSONObjectWithData:data
                             options:NSJSONReadingAllowFragments
                             error:&error];

    if (!jsonDic) 
    {
        return;
    }
    // process the JSON
}];
[downloadTask resume];

【讨论】:

    【解决方案2】:

    您的 JSON 在数据前有空格:

        [{"id":"37",
    

    检查您的服务器。

    【讨论】:

    • 问题是滥用NSURLConnectionDelegate 协议。
    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多