NSJSONSerialization获取错误“索引1超出空数组的边界”

时间:2016-06-02 11:49:01

标签: ios objective-c iphone ipad

有时我会在此行收到错误“索引1超出空数组的界限”

NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

这是我的完整代码

+ (NSDictionary *)getJson: (NSString *)strURL parameters:(NSDictionary *)parameters{
    NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:15.0];

    NSDictionary *headers = @{ @"content-type": @"application/json",
                               @"cache-control": @"no-cache",
                               @"postman-token": @"374a4b6f-b660-78f2-78bf-e22cf0156d8d"};

    [request setHTTPMethod:@"POST"];
    [request setAllHTTPHeaderFields:headers];
    [request setHTTPBody:postData];

    NSURLResponse *response;
    NSError *error;

    NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];*

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
    return json;
}

有时我会收到错误,有时候不会。我不明白?请帮助我,谢谢大家。

2 个答案:

答案 0 :(得分:0)

如果您收到上述错误,请尝试以下操作:

NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];

if (error)
{
    //1. See what the error says
    NSLog(error.localizedDescription);

    //2. Convert the original data into a string
    NSString *jsonString = [[NSString alloc] initWithData:aData encoding: NSUTF8StringEncoding];

    //Now take this string and validate it as a JSON at a place like http://jsonlint.com/
}

答案 1 :(得分:0)

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url
                                                                cachePolicy: defaultCachePolicy
                                                            timeoutInterval: defaultTimeoutInSeconds];

使用defaultCachePolicy更改您的cachePolicy并尝试:)