【问题标题】:JSON text did not start with array or object and option to allow fragments not setJSON 文本未以数组或对象开头,并且允许未设置片段的选项
【发布时间】:2016-03-01 07:15:53
【问题描述】:

您好,我是 iOS 新手,我正在尝试使用 JSON 从 Web 服务获取响应,但出现以下错误。请帮我解决。

Error Domain=NSCocoaErrorDomain Code=3840 "无法执行该操作 完全的。 (Cocoa 错误 3840。)”(JSON 文本不是以数组开头或 允许未设置片段的对象和选项。) UserInfo=0x7fd30bee0f70 {NSDebugDescription=JSON 文本不是以数组或对象开头并且 允许未设置片段的选项。,NSUnderlyingError=0x7fd30bede7b0 “请求失败:内部服务器错误 (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;
 }];
}

【问题讨论】:

  • json是什么样子的
  • 知道我没有从服务器得到任何响应,所以我不知道响应是哪种格式
  • 我更改了上面的代码,但仍然出现错误,错误是 serialization.response Code=-1011 "Request failed: internal server error (500)"
  • 错误可能在服务器端。尝试使用邮递员或任何其他应用程序使用您的params 作为参数来模拟您的发布请求。
  • 请检查我在下面发布的代码,如果有任何问题,请告诉我。 :)

标签: ios json objective-c web-services cocoa-touch


【解决方案1】:

这个解决了我的问题。

let json = try JSONSerialization.jsonObject(with: jsonData, options: [.fragmentsAllowed])

【讨论】:

    【解决方案2】:

    如果您的 url 没有足够的错误导致 api 返回错误或错误响应,但存在包含 api 不喜欢的奇怪内容的错误,也会发生此错误。例如:

    示例 1: appendingPathExtension(".json") 可能会添加一个额外的不需要的“..”句点,因为此方法已经为您添加了“点”。

    示例 2: url 是通过使用 URLQueryItem 类和 .queryItems 方法以外的方法将查询添加为 url/string 来构造的。在 Swift 5 中,这可能会导致“?”在您要求成为不同符号的请求中,或者让 api 一起错过您的 apiKey 或 queryItem。所以你在任何地方看到“?”在您的示例请求 url 中,确保使用 queryItems(请参阅文档)。

    这是一个成功的 URL 构建示例,其中包括一个查询项,即最后的 api_key...

        let heirarchyURL = baseURL.appendingPathComponent("league").appendingPathComponent("hierarchy").appendingPathExtension("json")
    
        var components = URLComponents(url: heirarchyURL, resolvingAgainstBaseURL: true)
    
        let keyQuery = URLQueryItem(name: "api_key", value: apiKey)
    
        components?.queryItems = [keyQuery]
    
        guard let url = components?.url else {
            NSLog("components of url failed to load properly")
            completion()
            return
        }
    
        print("fetch URL: \n\(url)\n")
    
        let request = URLRequest(url: url)
    
        URLSession.shared.dataTask(with: request) { (data, _, error) -> Void in
    

    【讨论】:

      【解决方案3】:

      这不是JSONSerialization 或快速错误。

      问题来自响应解析。您正在尝试反序列化 JSON 响应(必须包含在 ArrayDictionary 中),但您的响应不是上述内容(很可能是一个简单的字符串)。

      尝试使用此代码打印出我们的服务器数据,以便轻松识别错误并解决此问题。

      URLSession.shared.dataTask(with: url) { (data, response, error) in
      
          if let jsonData = data {
              do {
                  let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: AnyObject]
              }
              catch let err{
                  print("\n\n===========Error===========")
                  print("Error Code: \(error!._code)")
                  print("Error Messsage: \(error!.localizedDescription)")
                  if let data = data, let str = String(data: data, encoding: String.Encoding.utf8){
                      print("Print Server data:- " + str)
                  }
                  debugPrint(error)
                  print("===========================\n\n")
      
                  debugPrint(err)
              }
          }
          else {
              debugPrint(error as Any)
          }
      
      }.resume()
      

      【讨论】:

      • 你在哪里声明这个? .mutableLeaves 在你的代码中
      • 这是JSONSerialization.ReadingOptions
      【解决方案4】:

      在我的情况下,我将 .jsonobject 选项设置为:array,这就是我收到此错误的原因。

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

      这是我的代码,我发送 [ ] 以获取选项,后来我从 array 更改为 .allowFragments

      我的解决方案是..

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

      【讨论】:

      • 这是什么 .allowFragments 当我将此行放在我的代码中时,此错误将出现 Type 'JSONSerialization.WritingOptions' has no member 'allowFragments'。
      • 在此处查看@vaibhav 答案,stackoverflow.com/questions/40057854/…
      【解决方案5】:

      我也有这个问题,但是如果您想确保这个问题来自服务器端或后端,请尝试使用邮递员访问 Web 服务并检查原始部分或预览部分中的响应。这些部分显示了我们使用 Web 服务获得的准确响应。预览部分显示确切的信息/问题,如行号、函数名称等。

      【讨论】:

        【解决方案6】:

        我在使用 AFNetworking 时遇到了同样的问题,这是因为来自服务器的响应包含字符串而不是 JSON 字典或数组。所以我通过添加下面的代码行来修复它

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
        

        希望它也对你有用。一切顺利:)

        【讨论】:

          【解决方案7】:

          我遇到了同样的问题,我收到了来自服务器的加密响应,我所做的事情解决了这个问题。

          manager.requestSerializer = [AFHTTPRequestSerializer serializer];
          manager.responseSerializer = [AFHTTPResponseSerializer serializer];
          

          试一试。

          【讨论】:

            【解决方案8】:

            这是解决方案,使用以下代码即可:

            //注意:使用 JSON 的 web 服务

            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;
            

            【讨论】:

              【解决方案9】:

              这通常是与后端相关的问题,json 格式不正确,在客户端您无能为力....

              虽然有时会在错误的参数发送到后端时发生这种情况,因此您可以检查所有参数是否正确(包括类型和值)

              【讨论】:

                【解决方案10】:

                尝试将content-type 设置为json

                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

                【讨论】:

                • 我正在编辑上面的代码,但仍然出现错误,error is serialization.response Code=-1011 "Request failed: internal server error (500)"
                • 它不起作用,发生同样的错误错误:错误域=com.alamofire.error.serialization.response Code=-1011“请求失败:内部服务器错误(500)”
                • @Birendra 似乎您没有以服务器预期的格式发送 JSON 数据。
                • 所以不是代码错误,而是json数据格式错误,我必须更改存储在json文件中的数据格式?
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-07-07
                • 1970-01-01
                • 2018-05-21
                • 2014-01-06
                • 1970-01-01
                相关资源
                最近更新 更多