How to convert QVariant to QJsonValue?

4.9k Views Asked by At

How to convert QVariant to QJsonValue? I know QVariant provide the toJsonValue function, but it did not perform as expected.

For example:

qDebug()<<QVariant(1.0).toJsonValue();
qDebug()<<QVariant("test").toJsonValue();

Both return:

QJsonValue(null)
QJsonValue(null)

Expect output:

QJsonValue(double, 1)
QJsonValue(string, "test")
2

There are 2 best solutions below

1
On BEST ANSWER

You can use this static function too:

QJsonValue::fromVariant( myVariant )

Check this link for more info.

2
On

You might do the following:

QVariant dblVariant(1.0);
QVariant strVariant("test");

QJsonValue dblJs(dblVariant.toDouble());
QJsonValue strJs(strVariant.toString());

Your approach doesn't work because variant object should have user type QJsonValue, but it doesn't. Therefore it returns default constructed QJsonValue object.