Search code examples
c++jsonqtqwebviewqjsonobject

How send a QJsonObject using QWebChannel in Qt


Im implementing a HTML wrapper in Qt using QWebChannel, and im sucessifully able to send string, but, i woud like to send a QJsonObject, Not a json string like "{a:1,b:2}" but a Qt QJsonObject. Is it possible?

the official documentation says

"No manual message passing and serialization of data is required," http://doc.qt.io/qt-5/qwebchannel.html

How can I emit a signal with a JsonObject instead of a string?

This is my QWebChannel connected class

class Mapa : public QObject{
    Q_OBJECT

    public:
        explicit Mapa();
        displayMessage(const QString &message);
    signals:
        updateText(const QString &text); // success :sends text
        updateJson( const QJsonObject   &json); // fail: sends null
        updateJsond(const QJsonDocument &jsondoc);// fail: sends null
    }
 }

and here is my main code

Mapa map;
// setup the channel
QWebChannel channel;
QObject::connect(&clientWrapper, &WebSocketClientWrapper::clientConnected, &channel, &QWebChannel::connectTo);

// setup the dialog and publish it to the QWebChannel
channel.registerObject(QStringLiteral("map"), &map);

map.updateText("text");// sends "text" string

QJsonObject j;
j["Altitude"]  = 10;

map.updateJson(j); // sends "null" string
QJsonDocument doc(j);
map.updateJsond(doc); // sends "null" string

Solution

  • Instead of using the QJson family objects, you can send QVariant objects to your Javascript code

    • QJsonObject = QVariantMap
    • QJsonArray= QVariantList

    You can use the .toVariantMap() and .toVariantList() methods easily to convert your objects from the JSON objects.