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.
Use toObject() to convert to a QJsonObject. The value is undefined. This is usually returned as an error condition, when trying to read an out of bounds value in an array or a non existent key in an object.
QJsonArray::QJsonArray(std::initializer_list<QJsonValue> args) Creates an array initialized from args initialization list. QJsonArray can be constructed in a way similar to JSON notation, for example: QJsonArray array = { 1, 2.2, QString() }; This function was introduced in Qt 5.4.
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));
we can do this in one line
QString strFromObj = QJsonDocument(jsonObject).toJson(QJsonDocument::Compact).toStdString().c_str();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With