Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize QJsonObject from QString

Tags:

c++

json

qt

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

like image 539
Ioan Paul Pirau Avatar asked Nov 07 '14 15:11

Ioan Paul Pirau


2 Answers

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;
}
like image 65
TheDarkKnight Avatar answered Nov 12 '22 17:11

TheDarkKnight


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;
like image 3
Joe Avatar answered Nov 12 '22 18:11

Joe