How to initialize QJsonObject from QString
QString data; // assume this holds the json stringQJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
If you want the QJsonObject...
QJsonObject ObjectFromString(const QString& in){ QJsonObject obj; QJsonDocument doc = QJsonDocument::fromJson(in.toUtf8()); // check validity of the document if(!doc.isNull()) { if(doc.isObject()) { obj = doc.object(); } else { qDebug() << "Document is not an object" << endl; } } else { qDebug() << "Invalid JSON...\n" << in << endl; } return obj;}
You have to follow this step
- convert Qstring to QByteArray first
- convert QByteArray to QJsonDocument
- convert QJsonDocument to QJsonObject
QString str = "{\"name\" : \"John\" }";QByteArray br = str.toUtf8();QJsonDocument doc = QJsonDocument::fromJson(br);QJsonObject obj = doc.object();QString name = obj["name"].toString();qDebug() << name;