Home > front end >  Converting a String to json in Swift. for sending in a websocket
Converting a String to json in Swift. for sending in a websocket

Time:02-08

I have a JS to send Json via websocket. as follows:

function senddata()
{
    var obj = {};
    var arrayOfRequests = [];
    arrayOfRequests.push({
        "id":22,                                                                            
        "repeat":false,
    })
    obj.DataReq = arrayOfRequests;
    var stringToSend = JSON.stringify(obj);
    websocketConnection.send( stringToSend );  
}

This code works as expected, and the server sends back the requested info.

I am trying to do the same thing in swift.

   func send(text: String) {
        let message = text 
        guard let json = try? JSONEncoder().encode(message), 
            let jsonString = String(data: json, encoding: .utf8)
        else {
            return
        }
        webSocketTask?.send(.string(jsonString)){ error in 
            if let error = error {
                print("Error sending message", error) 
            }
        }
    }
send(text: "{“DataReq”:[{“id”:22,“repeat”:false}]}")

With this the server does not send any response.

If Connect both of these examples to a websocket echo server

the JS code sends {"DataReq":[{"id":22,"repeat":false}]}

while the Swift codes send "{"DataReq":[{"id":9,"repeat":false}]}".

any help is appreciated.

CodePudding user response:

Encoding a JSON string to JSON is pointless. Remove the encoding part

func send(text: String) {
    webSocketTask?.send(.string(text)){ error in 
        if let error = error {
            print("Error sending message", error) 
        }
    }
}

And in the send line the double quotes are invalid. Use this syntax

send(text: #"{"DataReq":[{"id":22,"repeat":false}]}"#)
  •  Tags:  
  • Related