How to create JSON from a dictionary in Swift 4?

99封情书 提交于 2019-12-01 05:47:58

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)

Additionally, you can just cast to String

let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let jsonString = String(data: jsonData!, encoding: .utf8)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!