How to initialize QJsonObject from QString How to initialize QJsonObject from QString json json

How to initialize QJsonObject from QString


Use QJsonDocument::fromJson

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

  1. convert Qstring to QByteArray first
  2. convert QByteArray to QJsonDocument
  3. 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;