Alamofire .post api error: Code=3840 "Invalid value around character 1

error domain=nscocoaerrordomain code=3840 swift 4
error 3840 alamofire
json serialization failed alamofire

Using Alamofire for .post api, api giving data in postman but not in my code. Posting below the code, please guide what wrong i am doing here:

// API calling method:

parameters = [
        "Address" : "" as AnyObject,
        "Name" :  "" as AnyObject,
        "ServiceID" : "" as AnyObject,
        "Rating" :  "" as AnyObject,
        "Price" :  "" as AnyObject
    ]

    let headers: Dictionary = [
        "" : ""
    ]

    print(parameters)

    ApiServices.requestPOSTURL(strURL, params: parameters, headers: headers, success:{

        (JSONResponse) -> Void in

        CommonMethodsClass.hideHUD(targetView: self.view)

        print(JSONResponse["message"])

        let strMsg = JSONResponse["message"].stringValue


        if (JSONResponse["status"].intValue == 1)
        {  

        }
        else
        {
            CommonMethodsClass.showAlertMessage(vc: self, titleStr: "Error!", messageStr: strMsg)
        }

    }) {
        (error) -> Void in
        print(error)

        CommonMethodsClass.hideHUD(targetView: self.view)
    }


// Api request method:
class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){

    Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { (responseObject) -> Void in

        print(responseObject)

        if responseObject.result.isSuccess {
            let resJson = JSON(responseObject.result.value as Any)
            success(resJson)
        }
        if responseObject.result.isFailure {
            let error : Error = responseObject.result.error!
            failure(error)
        }
    }
}

Error: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.}))

Update: Response to parse, may also needs to be changed.

{
    "status": true,
    "message": "",
    "data": [
        {
            "SalonID": "1",
            "SalonName": "Affinity",
            "SalonEmail": "vay.chaan@th-rce.com",
            "SalonPhone": "9999888877",
            "SalonMobile": "9999888877",
            "SalonAddress": "C-28, Sec-58, India",
            "Latitude": "18.5806",
            "Longitude": "27.36273",
            "Image": null,
            "SalonImage": "",
            "TimeIntervalminutes": 20,
            "AverageRating": 4,
            "IsActive": 1
        },
        {
            "SalonID": "3",
            "SalonName": "Looks",
            "SalonEmail": "rad@th-rce.com",
            "SalonPhone": "99998828877",
            "SalonMobile": "99998388877",
            "SalonAddress": "GP Mall,India",
            "Latitude": "",
            "Longitude": "",
            "Image": null,
            "SalonImage": "",
            "TimeIntervalminutes": 30,
            "AverageRating": 5,
            "IsActive": 1
        }
    ]
}

Replace responseJSON with responseString.

You need to convert the string for values. Can you update the string in your question?

You can use this function to convert response string into JSON:

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

String: let str = "{\"name\":\"James\"}"

USAGE: let dict = convertToDictionary(text: str)

ios, jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "​Invalid Alamofire.request(bannerURL, method: .post, parameters: params, encoding: i got same issue ..issue only with first time.. i solved it by calling two api call  Dismiss Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Try responseString instead of responseJSON and it will work

Alamofire.request("URL").responseString { response in
    print(response)

    if let json = response.result.value {
        print("JSON: \(json)")
    }
}

FAILURE: responseSerializationFailed(Alamofire.AFError , Hi Dear @mattt : when I used Alamofire 3.3.1 by Xcode 7.3,I get some questions . Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not POST, url, parameters: dic, encoding: . Your error message is encouraging you to use options: . The reason I have debugged is that below code does not sets the POST method in HTTPMethod property of URLRequest request.URLRequest.HTTPMethod = result.method.rawValue I tried setting String value explicitly, but the same issue.

Change responseJSON to responseString and it will work :)

  Alamofire.request("URL").responseString { response in
            print(response)

            if let json = response.result.value {
                print("JSON: \(json)")
            }
        }

Alamofire Domain=NSCocoaErrorDomain Code=3840 · Issue , Alamofire .post api error: Code=3840 "Invalid value around character 1 - ios. Dismiss Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Alamofire .post api error: Code=3840 "Invalid value - iOS, Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." Alamofire.request(url, method: .post, parameters: body, encoding:​  The build target for Alamofire will be listed as either Alamofire iOS, Alamofire macOS, Alamofire tvOS or Alamofire watchOS. And that’s it! The Alamofire.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.

ERROR: NSDebugDescription=Invalid value around character 0 , jsonSerializationFailed( Error Domain=NSCocoaErrorDomain Code=3840 "​Invalid I thought I'd post something on here since I haven't posted since I got hired  github "Alamofire/Alamofire" ~> 5.1 Swift Package Manager The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Nil response from JSON using Alamofire : swift, jsonSerializationFailed (Error Domain = NSCocoaErrorDomain Code = 3840 Оценка. 0. Ваш ответ недействительный json, следовательно, вы получаете эту ошибку. Пожалуйста Alamofire.request(urlString, method: .post, parameters: params as? [String:Any] Вы можете узнать больше response methods here. What did you do? ℹ I was implementing a RequestInterceptor and the adapt on 5.0.0-rc.3 does not update the request headers. What did you expect to happen? ℹ I checked on the server and I would expect the header to contain the token but i

Comments
  • change responseJSON to responseString
  • but same code is working for another api
  • I think this API response is different than that API. That's why its not able to get. Alamofire found some suspicious value to the receiving type that's why it is giving this error.
  • Try responseString instead of responseJSON and it will work
  • yes, it's working strange. thanks
  • Please check question, now
  • can you please guide in parsing?