3

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")
JustWe
  • 4,250
  • 3
  • 39
  • 90

2 Answers2

5

You can use this static function too:

QJsonValue::fromVariant( myVariant )

Check this link for more info.

Musa
  • 474
  • 4
  • 9
0

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.

vahancho
  • 20,808
  • 3
  • 47
  • 55
  • I thought Qt should be "smarter", able to detect the data type. – JustWe Dec 08 '17 at 08:06
  • There is nothing about being smart in this case. If you have value `1.0` it's impossible to say whether it meant to be a double or QJsonValue unless you explicitly specify the type of the variant. If you need to let Qt know that QVariant stores QJsonValue you have to construct QVariant out of QJsonValue with `QVariant::QVariant(const QJsonValue &val)`. In that case `toJsonValue()` will work properly. – vahancho Dec 08 '17 at 08:14