jsonswiftwebsocketswifty-json

How can I convert a JSON as Data Type in Swift?


I want to send data to my websocket server in swift but the websocket server write function only accepts strings or the data type. Since I did not find any JSON.stringify option for swift I used swiftyJson to create my own type of JSON, but now I need to convert it to data in order to be able to send it to the server.

var json: JSON =  ["name": "Jack", "age": 25]
socket?.send(data: json //<-- This needs to be Data)

I tried wrapping the JSON in Data(json) but this did not work either. Any ideas? I have swiftyJson installed if there is a solution for this.


Solution

  • The simplest way is a literal

    let json =  #"{"name": "Jack", "age": 25}"#
    let data = Data(json.utf8)
    

    With SwiftyJSON it's pretty simple, too, but less efficient.

    let json: JSON =  ["name": "Jack", "age": 25]
    let data = try! json.rawData()