如何从 Swift 4 中的字典创建 JSON?

How to create JSON from a dictionary in Swift 4?

编辑:我已经阅读了关于同一问题的其他答案,但是我无法获得所需的输出。我已经尝试了其他问题中建议的许多变体,但它不起作用。

我有一个 JSON 片段,当我打开 websocket 时需要将其添加为正文。

sender: "system1@example.com",
recipients:"system2@example.com",
data: {
    text: "Test Message"
},

所以使用 Swift 我做了以下操作,

var messageDictionary : [String: Any] = [
    "sender": "system1@example.com",
    "recipients":"system2@example.com",
    "data": [
        "text": "Test Message"
    ],
]
do {
    let jsonData = try JSONSerialization.data(withJSONObject: messageDictionary, options: .prettyPrinted)
    let jsonString = String(data: jsonData, encoding: String.Encoding.ascii)
    socket.write(string: jsonString!)
    print(jsonString)
} catch {
    print(error.localizedDescription)
}

当我打印 jsonString 时,我得到

Optional("{\n  \"sender\" : \"system1@example.com\",\n  \"data\" : {\n    
    \"text\" : \"Test Message\"\n  },\n  \"recipients\" : 
    \"system2@example.com\"\n}")

作为控制台输出。我希望上面的代码片段被格式化为 JSON。 如何在没有 /n 和额外空格的情况下获得正常 JSON 的输出? 我正在使用 Swift 4 和 Xcode 9.1

编辑 2:

let jsonData = try JSONSerialization.data(withJSONObject: messageDictionary, options: []) 让 decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])

我尝试执行上述操作并得到以下输出:

{
    data =     {
        text = Test Message;
    };
    recipients = "system1@example.com";
    sender = "system2@example.com";
}

但是 websocket 期望这样:

{ "sender":"system1@example.com","recipients":
["system2@example.com"],"data":{"text":"Test Message"}}

即使有轻微的变化,如双引号错位,websocket 服务器也不接受输入。如何以这种方式准确格式化 JSOn 以便 websocket 可以接受它?

在尝试了各种方法后,以下方法对我来说很管用,可以获取后端所需的确切格式。

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)

此外,您可以转换为字符串

let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let jsonString = String(data: jsonData!, encoding: .utf8)

现在 JSONEncoder 可以轻松完成这项工作。

let encoder = JSONEncoder()

encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(yourDictionary)

print(String(data: data, encoding: .utf8)!)