How to initialize a QJsonObject from a QString

I am new to Qt and I have a very simple operation that I want to do: I have to get 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"] } ] } 

JSon was verified with this syntax check and validation check: http://jsonformatter.curiousconcept.com/ and was validated.

I used QJsonValue to initialize String for this and converted it to QJSonObject:

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

I download JSon inserted 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 is definitely a good way to do this because it does not work, and I did not find any useful examples.

+5
source share
1 answer

Use QJsonDocument :: fromJson

 QString data; // assume this holds the json string QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8()); 

If you want a 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; } 
+15
source

Source: https://habr.com/ru/post/1206435/


All Articles