Ashish Ashish - 28 days ago 5
JSON Question

How to save incoming string (coming through web-socket) into Json file in QT c++?

I am getting the message in my client side (echoclient.cpp) in string format. I want to save that string information into the JSON file. So that, I can various operation according to the JSON information. Here is my echoclient.cpp file code

using namespace std;
QT_USE_NAMESPACE

EchoClient::EchoClient(const QUrl &url, bool debug, QObject *parent) :
QObject(parent),
m_url(url),
m_debug(debug)
{
if (!m_debug)
qDebug() << "WebSocket server:" << url;
connect(&m_webSocket, &QWebSocket::connected, this, &EchoClient::onConnected);
connect(&m_webSocket, &QWebSocket::disconnected, this, &EchoClient::closed);
m_webSocket.open(QUrl(url));
}

void EchoClient::onConnected()
{
if (!m_debug) //condition check for connection is there
qDebug() << "WebSocket connected";
connect(&m_webSocket, &QWebSocket::textMessageReceived,this, &EchoClient::onTextMessageReceived); //connect to another slot function
}

void EchoClient::onTextMessageReceived(QString message) {
if(message.contains("date")){
qDebug()<<"message received :"<<message<<endl;
}
else{
jsonstringflag = message;
cout<<"echo..."<<endl;
}
}


Now I want to save this message (which contains "date") in a new JSON file.Please give me some suggestions to solve this problem.

Answer

QJsonValue has a private constructor to prevent wrong implicit typecasting:

QJSonValue::QJsonValue(const void *);

Perhaps your compiler is interpreting "10" as a pointer value, since QJsonValue doesn't take integers. Try assigning a double instead:

[object Object] = 10.0;

And will changing this value still allow me to write the entire JSON document back to the file with the new value? Simply write your updated QJsonValue back into your QJsonObject, convert that into a QJsonDocument, then write it to a file. For example

    value = 10.0;
jo["myValue"] = value;
jsonDoc.setObject(jo);

configFile.resize(0); // Erase old contents
configFile.write(jsonDoc.toBinaryData());
Comments