JSON Text Did Not Start with Array or Object and Option to Allow Fragments Not Set

JSON text did not start with array or object and option to allow fragments not set on Swift async function

Seems like there are two types of cloud functions that can receive my request and each one will get it in a different way so there are two ways to approach this issue.

The first one is to change the way I send the parameter. So instead of using an array, I'll send it as part of the function name like this:

let result = try await functions.httpsCallable("addMessage?text=\(data)").call()

The second way is to use an 'onCall' method on the cloud function like this which will get the array (i prefer this solution as it feels more secured):

exports.addMessage = functions.https.onCall((data, context) => {

const original = data.text;

...

return {...};
});

JSON text did not start with array or object and option to allow fragments not set.

So finally I was able to detect the issue. The issue was in the subdomain part of the URL.

https://first.yyyy.com/question/abc

Since I was using the session id of another sub-domain [OpenTok] and passing it as a parameter in this, Status code 500 appeared.

https://second.yyyy.com/question/abc

Also, I changed my POST function structure to this:

    func startArchive() {

let app_Id = (appId.base64Decoded()!)
let job_Id = (jobId.base64Decoded()!)

let parameters: [String: Any] = ["session_id": pSessionId, "job_id":job_Id, "app_id":app_Id, "action":"start"]

print("Parameter:\(parameters)")
guard let url = URL(string: "https://first.yyyy.com/question/abc") else {return}

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("iOS", forHTTPHeaderField: "deviceType")
guard let httpbody = try? JSONSerialization.data(withJSONObject: parameters, options:[]) else {return}
request.httpBody = httpbody

let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if let response = response {
print(response)
}
if let data = data{

let mdata = String(data: data, encoding: .utf8)
print("This is data: \(mdata!)")

do{
// print("\(String(data: data, encoding: .utf8) ?? "")")
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
DispatchQueue.main.async {
_archiveId = (json["archive_id"] as! String)
print(json)
}
}
} catch {
print(error)
}
}
}.resume()
}

It worked fine for me and returned the data in JSON.

iOS URLSession Error JSON text did not start with array or object and option to allow fragments not set.

Luckily I found the solution for my own problem. I missed to understand the error. As it says "option to allow fragments not set.", What I did was adding option .allowFragments. So the whole line after this replacement,

let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

And I could solve the problem and get the answer PHP returns.

Alamofire file upload getting error JSON text did not start with array or object and option to allow fragments not set

Use Alamofire

let upload_url = "your url"
let fieldName = "UploadedFile"
let mimeType = "plain/text"

Alamofire.upload(multipartFormData: { multipartFormData in

//you can add multiple file
multipartFormData.append(fileData as Data, withName: fieldName, fileName: fileName, mimeType: mimeType)

}, to: upload_url, method: .post, headers: ["Authorization": "auth_token"],

encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let _ = self else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
debugPrint("uploaderService error:\(encodingError)")
}

})

Having Error 3840 JSON text did not start with array or object and option to allow fragments not set. after a while on the application

The problem was how I was checking what the manager was returning, checking it the wrong way made it try to do things with a null object.

The solution was to change if (objects != []) { to if let objs = objects { and it works now.

Error Code : Error Domain=NSCocoaErrorDomain Code=3840 JSON text did not start with array or object and option to allow fragments not set.

It clearly says you have sent wrong JSON format. Means there is two
possibility.

  • Either you have sent wrong json.

  • Or your server unable to parse data from your request.

I have already faced the same issue. Please use the below code, I am sure it will work for you.

NSInteger intUserID = [[prefs stringForKey:@"user_id"] integerValue];
NSInteger intProdID = [_strProdID integerValue];
NSDictionary *params = @{@"In d":@(1),@"user_id":@(intUserID),@"product_id":@(intProdID)};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];

if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager.requestSerializer = serializer;

[manager PUT:@"http://api.XXX.com/api/product/wishlist_add" parameters:jsonString success:^(NSURLSessionTask *task, id responseObject) {
}failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error Code : %@", error);
}];
}

Find reference from here

Update:

It is working fine. Please see below attached screenshot.

enter image description here

Please ensure user_id and product_id value should not be nil



Related Topics



Leave a reply



Submit