0

I'm making a request to remote server using RESTful API. I create a dictionary then I use JSONSerialization to serialize it to Data. The problem is when serialize date time dd/mm/yyyy it automatically add a \ character. This problem may be due to the convert from Dictionary to Data or Data to String. I don't know exactly.

How to remove this \ character

Below are my code on app:

var dic = [String : String]()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss"
let current : String = dateFormatter.string(from: now)       
dic["RequestAt"] = current
// others set key-value
do {
    var request = URLRequest(url: URL(string: DOMAIN_NAME)!)
    request.httpMethod = "POST"
    request.timeoutInterval = 3
    request.addValue("application/json charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json charset=utf-8", forHTTPHeaderField: "Accept")
    let d = try JSONSerialization.data(withJSONObject: dic, options: [])
    let str = String.init(data: d, encoding: .utf8)
    print(str ?? "NOTHING") // Same result as server's receive
    request.httpBody = d
    let session = URLSession.shared

    session.dataTask(with: request) { data, response, err in
        //handle callback
    }.resume()

} catch let error {        
    print(error.localizedDescription)
}

But server-side receive below json:

{
    "RequestAt":"08\/04\/2017 11:42:03",
    ....
}

Thank you for your support.

Robust
  • 2,415
  • 2
  • 22
  • 37
  • Are you concerned about the backslashes or doesn't the server accept the format? According to the JSON specs slashes can be escaped – vadian Apr 08 '17 at 17:17
  • the developer of server-side feedback me this problem. This system already has an app run on Android, so I must correct this step. – Robust Apr 08 '17 at 17:21
  • Escaping forward slashes is perfectly valid so it should be corrected on the server-side. – vadian Apr 08 '17 at 17:23

2 Answers2

0

You could go around the problem by trimming the string.

current = current.stringByTrimmingCharactersInSet(NSCharacterSet.init(charactersInString: "\"))
Alex Ioja-Yang
  • 1,428
  • 13
  • 28
0

I decided to use Alamofire for making request. It just a temporary solution because It must use the third party library.

What I do now:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss"
let current : String = dateFormatter.string(from: now)   
let parameters: Parameters = [
    "RequestAt": current,
     ...
]

// Both calls are equivalent
Alamofire.request(DOMAIN_NAME, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
    //handle callback
}
Robust
  • 2,415
  • 2
  • 22
  • 37