Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a QJsonObject to QString

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.

like image 598
gogo000 Avatar asked Jan 27 '15 22:01

gogo000


People also ask

How do you convert QJsonValue to QJsonObject?

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.

What is QJsonArray?

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.


2 Answers

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));
like image 70
TheDarkKnight Avatar answered Sep 23 '22 05:09

TheDarkKnight


we can do this in one line

QString strFromObj = QJsonDocument(jsonObject).toJson(QJsonDocument::Compact).toStdString().c_str();
like image 44
SayAz Avatar answered Sep 24 '22 05:09

SayAz