c++jsonqt

How to initialize QJsonObject from QString


I am quite new to Qt and I have a very simple operation that I want to do: I have to obtain the following JSonObject:

{
    "Record1" : "830957 ",
    "Properties" :
    [{
            "Corporate ID" : "3859043 ",
            "Name" : "John Doe ",
            "Function" : "Power Speaker ",
            "Bonus Points" : ["10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56 ", "10", "45 ", "56", "34 ", "56", "45"]
        }
    ]
}

The JSon was checked with this Syntax and Validity checker: http://jsonformatter.curiousconcept.com/ and was found valid.

I used QJsonValue initialization of String for that and converted it to QJSonObject:

QJsonObject ObjectFromString(const QString& in)
{
    QJsonValue val(in);
    return val.toObject();
}

I am loading the JSon pasted up from a file:

QString path = "C:/Temp";
QFile *file = new QFile(path + "/" + "Input.txt");
file->open(QIODevice::ReadOnly | QFile::Text);
QTextStream in(file);
QString text = in.readAll();
file->close();

qDebug() << text;
QJsonObject obj = ObjectFromString(text);
qDebug() <<obj;

There's most certainly a good way to do this because this is not working, and I didn't find any helpful examples


Solution

  • Use QJsonDocument::fromJson:

    QString data; // assume this holds the json string
    
    QJsonDocument 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;
    }