Issue
With the following line i am converting a dict to json string:
let dummyCom = ["companyId" : company.getCompanyId()?.stringValue]
var error : NSError?
let jsonData = try! JSONSerialization.data(withJSONObject: dummyCom, options: JSONSerialization.WritingOptions.prettyPrinted)
var jsonString = String(data: jsonData, encoding: String.Encoding.utf8) // the data will be converted to the string
I am getting the below description:
Printing description of jsonString:
▿ Optional<String>
- some : "{\n \"companyId\" : \"1\"\n}"
My question is how can i remove \n and \ from string.
I have tried this:
jsonString = jsonString!.removingPercentEncoding
but getting same result.
Any help or suggetion would be helpfull
Solution
Just replace JSONSerialization.WritingOptions.prettyPrinted
with []
And you will get:
"{"companyId":1}"
And your code will look like:
let dummyCom = ["companyId" : 1]
var error : NSError?
let jsonData = try! JSONSerialization.data(withJSONObject: dummyCom, options: [])
var jsonString = String(data: jsonData, encoding: String.Encoding.utf8)
Answered By – Dharmesh Kheni
Answer Checked By – Mary Flores (BugsFixing Volunteer)