ios NSJSONSerialization字符0前后的值无效

k5ifujac  于 2023-01-14  发布在  iOS
关注(0)|答案(2)|浏览(91)

我从服务器执行get操作,得到一个有效的响应:

- (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应用程序工作良好.*
    *解决

感谢@希曼舒乔希:

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

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

7d7tgy0s

7d7tgy0s1#

我遇到了同样的问题,但这是因为我的初始网址不正确。
在解析JSON之前,需要检查响应,它可能会告诉您未找到它。
此时,数据实际上可以包含一个404 HTML页面。
我使用这些方法来调试这个问题,并使用更简单的方法来处理Web请求:

// 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];
vmdwslir

vmdwslir2#

您的JSON在数据前面有白色:

[{"id":"37",

检查您的服务器。

相关问题