0

I am using the below post method to send JSON array, Please help to me solved below issue?

I need post json data like below ;

key = punchdata

{
    "maids" : "649",
    "misReason" : "test",
    "uId" : "20",
    "aDate" : "2020-04-24",
    "punchArray" : [
      {
        "in_time" : "14:10:00",
        "in_date" : "2020-04-24",
        "out_date" : "2020-04-24",
        "out_time" : "19:00:00"
      }
    ]
  }

Below I attached the postman request and response, please check ;

enter image description here

func sendJSONArrayToPost()   {

        let params2 = ["punchdata" : ["uId": "20",
                      "aDate":"2020-04-24",
                      "maids":"649",
                      "misReason":"test",
                      "punchArray": [
                        [
                            "in_date": "2020-05-07",
                            "in_time": "10:00:00",
                            "out_date": "2020-05-07",
                            "out_time": "13:00:00"
                        ]]]] as [String : Any]

        let url = "https://iiplccr.hrgird.com/owner/hrmessapi/applymissingPunch"

        Alamofire.request(url, method: .post, parameters: params2, encoding:JSONEncoding.default, headers: nil)
            .responseJSON { response in
                debugPrint(response)
                if let data = response.result.value{
                    if  (data as? [String : AnyObject]) != nil{
                        if let dictionaryArray = data as? Dictionary<String, AnyObject?> {
                            if dictionaryArray.count > 0 {
                                var resCode = Int()
                                var resMessage = ""

                                if let success = dictionaryArray["success"] as? Int{
                                    resCode = success
                                }
                                if let Msg = dictionaryArray["Msg"] as? String{
                                    resMessage = Msg
                                }
                            }
                        }
                    }
                }
        }
}

Other Way :

let jsonDataDict: NSMutableDictionary = NSMutableDictionary()

            let arrObj: NSMutableDictionary = NSMutableDictionary()
            let jsonArrayDict: NSMutableArray = NSMutableArray()

            jsonDataDict.setValue("\(mLoginUserId)", forKey: "uId")
            jsonDataDict.setValue(dateArray[0], forKey: "aDate")
            jsonDataDict.setValue(maidStr, forKey: "maids")
            jsonDataDict.setValue(resason, forKey: "misReason")

            for item in self.MissingPunchListArray {
                arrObj.setValue(item.inDate, forKey: "in_date")
                arrObj.setValue(item.inTime, forKey: "in_time")
                arrObj.setValue(item.outDate, forKey: "out_date")
                arrObj.setValue(item.outTime, forKey: "out_time")
                jsonArrayDict.add(arrObj)
            }
            jsonDataDict.setValue(jsonArrayDict, forKey: "punchArray")

below is another function I am trying to do ;

let url = "https://iiplccr.hrgird.com/owner/hrmessapi/applymissingPunch"
var request = URLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")  
request.httpBody = try! JSONSerialization.data(withJSONObject: ["punchdata": jsonDataDict])

Alamofire.request(request)
    .responseJSON { response in
        switch response.result {
        case .failure(let error):
            print("error: \(error)")

            if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
                print("responseString: \(responseString)")
            }
        case .success(let responseObject):
            print("responseObject: \(responseObject)")
        }
}

I get below error:

[Data]: 37025 bytes
[Result]: FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
Kiran Jadhav
  • 3,209
  • 26
  • 29
  • Does this answer your question? [Sending json array via Alamofire](https://stackoverflow.com/questions/27026916/sending-json-array-via-alamofire) – elliott-io May 10 '20 at 07:47
  • @elliott-io, I am trying with your solution but not work, please help to resolve the above issue. I need to send data in JSON format. thanks. – Kiran Jadhav May 10 '20 at 07:50
  • There are many solutions to sending an array to alamofire with swift 3. Did you try this one? https://stackoverflow.com/questions/36563371/send-an-array-as-a-parameter-in-a-alamofire-post-request – elliott-io May 10 '20 at 07:53
  • @elliott-io Yes, but not work. responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})) – Kiran Jadhav May 10 '20 at 07:54
  • Please post your other code that you tried. – elliott-io May 10 '20 at 07:58
  • @elliott-io I posted another way I am trying. If you have a better way please let me know, thanks. – Kiran Jadhav May 10 '20 at 08:11
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213547/discussion-between-kiran-jadhav-and-elliott-io). – Kiran Jadhav May 10 '20 at 11:01
  • `[Data]: 37025 bytes` what's the response data in string? IO checked, and it's not JSON, but HTML code: `" \r\n \r\n \r\n \r\n – Larme May 10 '20 at 13:35
  • @Larme, You can use below URL: let URL = "https://iiplccr.hrgird.com/owner/hrmessapi/applymissingPunch" – Kiran Jadhav May 10 '20 at 13:58
  • You did `print("responseString: \(responseString)")`, please tell us what the output of that. – Larme May 10 '20 at 14:01
  • @Kiranjadhav In Postman, if it's working, can you click on "Code" (right screen) and share the generate Swift code? Or curl one? – Larme May 10 '20 at 14:07
  • @Larme Okay, I will share it with you. please share your email id, so I will send you mail for the same. – Kiran Jadhav May 11 '20 at 10:28
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213606/discussion-between-kiran-jadhav-and-larme). – Kiran Jadhav May 11 '20 at 10:31

1 Answers1

0

You can try this way

var JsonDic = [String:Any]()

JsonDic["maids"] = "649"
JsonDic["misReason"] = "test"
JsonDic["uId"] = "20"
JsonDic["aDate"] = "2020-04-24"

let arr = [[String: String]]()
var obj = [String: String]()
obj["in_time"] = "14:10:00"
obj["to_city_id"] = "2020-04-24"
obj["out_date"] = "2020-04-24"
obj["out_time"] = "19:00:00"
arr.append(obj)


JsonDic["punchArray"] = arr
  • It give me error: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})) – Kiran Jadhav May 10 '20 at 11:08