Edit: I have read the other answers on SO for the same issue , however Im unable to get the desired output. I have tried many variations as suggested in other questions but
After trying out various ways the below way is what worked for me for getting the exact format required by the backend.
var messageDictionary = [
"sender":"system1@example.com",
"recipients":["system2@example.com"],
"data":[
"text" : data
]
] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: messageDictionary)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)
Now JSONEncoder can do the work easily.
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(yourDictionary)
print(String(data: data, encoding: .utf8)!)
Additionally, you can just cast to String
let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let jsonString = String(data: jsonData!, encoding: .utf8)