I want to add more than one QJsonObject and not QJsonArray to a QJsonDocument. Is this possible? It should look like this:
{
"Obj1" : {
"objID": "111",
"C1" : {
"Name":"Test1",
"Enable" : true
}
},
"Obj2" : {
"objID": "222",
"C2" : {
"Name":"Test2",
"Enable" : true
}
}
}
I have refered this but I dont want to use JsonArray
. Only want to use JsonObject
. I have also refer many more answer over here, but dint find any solution.
I tried this :
QTextStream stream(&file);
for(int idx(0); idx < obj.count(); ++idx)
{
QJsonObject jObject;
this->popData(jObject); // Get the Filled Json Object
QJsonDocument jDoc(jObject);
stream << jDoc.toJson() << endl;
}
file.close();
Output
{
"Obj1" : {
"objID": "111",
"C1" : {
"Name":"Test1",
"Enable" : true
}
}
}
{
"Obj2" : {
"objID": "222",
"C2" : {
"Name":"Test2",
"Enable" : true
}
}
}
In the loop, with each iteration you are creating a new JSON document and writing it to the stream. That means that they all are multiple independent documents. You need to create one
QJsonObject
(the parent object) and populate it with all the other objects as part of it i.e. nested objects. Then, you'll have only one object and after the loop you can create aQJsonDocument
and use it to write to file.Here's your code that creates a new document with each iteration:
Here's what you need to do:
Here's a small working example:
Output: