JSON text did not start with array or object and o

2020-06-03 03:32发布

Hi I am new in iOS and I am trying to get response from web-service using JSON but following error occurs. Please help me to solve it.

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7fd30bee0f70 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x7fd30bede7b0 "Request failed: internal server error (500)"}

-(void)loadFeedWithOffset:(NSInteger)Offset Limit:(NSInteger)Limit
{
     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

//      [manager.requestSerializer setValue:@"application/json;                 text/html" forHTTPHeaderField:@"Accept"];
//      [manager.requestSerializer setValue:@"application/json;     text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"user_id"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Offset] forKey:@"offset"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Limit] forKey:@"limit"];
    [params setValue:[NSString stringWithFormat:@"%d",[AppDelegate sharedAppDelegate].intPostType] forKey:@"post_type"];

    [manager POST:[NSString stringWithFormat:@"%@webservices/post/load", API_URL] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
 {

     NSLog(@"JSON: %@", responseObject);
     if ([[responseObject objectForKey:@"status"] isEqualToString:@"fail"])
     {
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[responseObject objectForKey:@"message"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
         [alert show];
         alert = nil;
     }
     else
     {
         if ([[responseObject objectForKey:@"feed"] count] > 0)
         {
             isOver = FALSE;
             [arrFeed addObjectsFromArray:[responseObject objectForKey:@"feed"]];
             searchedDataArray = [NSMutableArray  arrayWithArray:arrFeed];
             //searchedDataArray=arrFeed;
             [tblMenuDetail reloadData];
         }
         else
         {
             isOver = TRUE;
         }
         [self performSelector:@selector(doneLoadingTableViewData) withObject:self afterDelay:1.0];
     }
     [[AppDelegate sharedAppDelegate] hideProgress];
 } failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     [[AppDelegate sharedAppDelegate] hideProgress];
     NSLog(@"Error: %@", error);
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
     [alert show];
     alert = nil;
 }];
}

9条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-06-03 04:09

Here is solution, Use below code and it will work:

//Note: web-service using JSON

NSString *strAPIURL = [NSString stringWithFormat:@"%@webservices/post/load", API_URL];

NSDictionary* dictHeader = @{@"content-type": @"application/json"};  //You can add here more header field if require, like "Authorization"

NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"user_id"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Offset] forKey:@"offset"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)Limit] forKey:@"limit"];
    [params setValue:[NSString stringWithFormat:@"%d",[AppDelegate sharedAppDelegate].intPostType] forKey:@"post_type"];



    NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strAPIURL]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:30.0];
    [request setHTTPMethod:@“POST”];
    [request setAllHTTPHeaderFields:dictHeader];
    [request setHTTPBody:postData];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);

       //Success code…

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    //Failure code…

    }];

    [operation start];

    return operation;
查看更多
Summer. ? 凉城
3楼-- · 2020-06-03 04:10

In my case i set .jsonobject options: as array, thats why i'm getting this error.

let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]

This is my code here i send [ ] for options, later i changed from array to .allowFragments

My solution is..

let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
查看更多
ら.Afraid
4楼-- · 2020-06-03 04:13

I also have this issue, but if you wants to make sure this issue is from server side or back end then try hitting web service using postman and check response in either Raw section or in Preview section. These sections shows exact response which we get using web service. Preview sections shows exact information / issue like line no, function name etc.

查看更多
登录 后发表回答