46

I have a QJsonObject data and want to convert to QString. How can I do this? Searched for help in Qt, it only can convert QJsonObject to QVariantMap...

Thanks in advance.

gogo000
  • 483
  • 1
  • 4
  • 8

3 Answers3

101

Remembering when I first needed to do this, the documentation can be a bit lacking and assumes you have knowledge of other QJson classes.

To obtain a QString of a QJsonObject, you need to use the QJsonDocument class, like this: -

QJsonObject jsonObj; // assume this has been populated with Json data

QJsonDocument doc(jsonObj);
QString strJson(doc.toJson(QJsonDocument::Compact));
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • 7
    It should probably be mentioned, that `QJsonDocument::toJson()` returns a UTF-8 formatted `QByteArray`. – marcbf Oct 18 '18 at 10:54
5

we can do this in one line

QString strFromObj = QJsonDocument(jsonObject).toJson(QJsonDocument::Compact).toStdString().c_str();
SayAz
  • 751
  • 1
  • 9
  • 16
0

When the macro QT_NO_CAST_FROM_ASCII is enabled, you can do something like:

QJsonDocument doc(jsonObject);
QByteArray docByteArray = doc.toJson(QJsonDocument::Compact);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
Qstring strJson = codec->toUnicode(docByteArray);

Or better, just use QLatin1String(QByteArray&), based on the example of TheDarkKnight:

QJsonDocument doc(jsonObj);
QByteArray docByteArray = doc.toJson(QJsonDocument::Compact);
Qstring strJson = QLatin1String(docByteArray);
jaques-sam
  • 2,578
  • 1
  • 26
  • 24