如何在Swift 4中从字典创建JSON? [英] How to create JSON from a dictionary in Swift 4?

查看:94
本文介绍了如何在Swift 4中从字典创建JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于相同的问题,我已经阅读了SO上的其他答案,但是我无法获得所需的输出.我已经尝试了其他问题中建议的许多变体,但没有用.

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 its not working.

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

I have a JSON snipped which needs to be added as the body when I open a websocket.

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

因此,使用Swift我做了以下事情,

So using Swift I did the following,

    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时,我得到

When I print the jsonString, I get

    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

as the console output. I expected the above snippet to be formatted as JSON. How to get the output as normal JSON without the /n and additional spaces? Im using Swift 4 and Xcode 9.1

编辑2 :

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

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

I tried doing the above and I get the following as the output:

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

但是Websocket期望这样:

However the websocket expects this:

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

即使有一些细微的变化(例如双引号的位置错位),websocket服务器也不接受输入.如何以这种方式精确格式化JSOn以便Websocket可以接受它?

Even with a slight variation like misplacing of double quotes the websocket server doesnt accept the input. How to exactly format the JSOn this way so that the websocket can accept it?

推荐答案

尝试了各种方法之后,下面的方法对我来说是获得后端所需的确切格式的有效方法.

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)

这篇关于如何在Swift 4中从字典创建JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆