ios JSON 文本未以数组或对象开头,并且没有设置允许片段的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33951401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON text did not start with array or object and option to allow fragments not set
提问by Birendra
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.
嗨,我是 iOS 新手,我正在尝试使用 JSON 从 Web 服务获取响应,但发生以下错误。请帮我解决它。
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)"}
错误域=NSCocoaErrorDomain 代码=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;
}];
}
回答by edo
This is usually a back-end related issue, the json is not well formated and there is nothing you can do about it on client side ....
这通常是与后端相关的问题,json 格式不正确,在客户端您无能为力....
Although sometimes this occurs when wrong parameters are sent to back-end, so you could check if all parameters are correct (both type and value)
虽然有时当错误的参数发送到后端时会发生这种情况,因此您可以检查所有参数是否正确(类型和值)
回答by Sreejith
Try setting the content-type
as json
尝试设置content-type
为json
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
回答by Satyendra Pandey
I was having same problem with AFNetworking, this is because your response coming from server is holding string and not JSON Dictionary or Array. So i fixed it by adding below line of code
我在使用 AFNetworking 时遇到了同样的问题,这是因为来自服务器的响应包含字符串而不是 JSON 字典或数组。所以我通过添加下面的代码行来修复它
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
Hope it may work for you too. All the best:)
希望它也对你有用。祝一切顺利:)
回答by AsimRazaKhan
I am having the same issue, I am getting an encrypted response from server, what I did solves the issue.
我遇到了同样的问题,我收到了来自服务器的加密响应,我所做的解决了这个问题。
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Give it a try.
试一试。
回答by Ajju
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.
我也有这个问题,但如果你想确保这个问题是来自服务器端或后端,那么尝试使用邮递员点击 Web 服务并检查原始部分或预览部分的响应。这些部分显示了我们使用 Web 服务获得的准确响应。预览部分显示确切的信息/问题,如行号、函数名称等。
回答by AshvinGudaliya
This is not JSONSerialization
or swift error.
这不是JSONSerialization
或快速错误。
The problem comes from response parsing. You are trying to de-serialize a JSON response (which MUST be contained in either a Array
or Dictionary
) however your response is none of the above (Most likely a simple string).
问题来自响应解析。您正在尝试反序列化 JSON 响应(必须包含在 aArray
或 中Dictionary
),但是您的响应不是上述任何一个(很可能是一个简单的字符串)。
try this code to print out our server data to easily identifying to error and resolve this.
尝试使用此代码打印出我们的服务器数据,以便轻松识别错误并解决此问题。
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()
回答by iOS
In my case i set .jsonobject options: as array, thats why i'm getting this error.
在我的情况下,我将 .jsonobject options: as array设置为数组,这就是我收到此错误的原因。
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
这是我的代码在这里我发送[]选项,后来我从数组更改为 .allowFragments
My solution is..
我的解决办法是..
let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
回答by John Pitts
This error also can occur if your url isn't faulty enough to cause the api to return an error or bad response, but having faults which contain something odd the api didn't like. For instance:
如果您的 url 没有足够的错误导致 api 返回错误或错误的响应,但包含包含 api 不喜欢的奇怪内容的错误,也会发生此错误。例如:
example 1: appendingPathExtension(".json") could add an extra unwanted ".." period, bc this method ALREADY adds the 'dot for you.
示例 1: appendingPathExtension(".json") 可能会添加额外的不需要的“..”句点,bc 此方法已经为您添加了“点”。
example 2: url was constructed by adding the query as url/string via a method other than using URLQueryItem Class and .queryItems method. In Swift 5 this can cause a "?" in your request to be a different symbol, or have the api miss your apiKey or queryItem alltogether. So anywhere you see "?" in your example request url, make sure to use queryItems (see documentation).
示例 2:通过使用 URLQueryItem 类和 .queryItems 方法以外的方法将查询添加为 url/string 来构造 url。在 Swift 5 中,这会导致“?” 在您要求成为不同符号的请求中,或者让 api 完全错过您的 apiKey 或 queryItem。所以你在哪里看到“?” 在您的示例请求 url 中,确保使用 queryItems(请参阅文档)。
Here's an example of successful URL construction including a single query item which is the api_key at the very end...
这是一个成功的 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
回答by Sandip Patel - SM
Here is solution, Use below code and it will work:
这是解决方案,使用下面的代码,它将起作用:
//Note: web-service using JSON
//注意:使用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;