How I can add more than one QJsonObject to a QJsonDocument - Qt

2k Views Asked by At

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
        }
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

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 a QJsonDocument and use it to write to file.

Here's your code that creates a new document with each iteration:

for ( /* ... */ )
{
    // ...
    QJsonDocument jDoc(jObject);        // new document without obj append
    stream << jDoc.toJson() << endl;    // appends new document at the end
    // ...
}

Here's what you need to do:

// Create a JSON object
// Loop over all the objects
//    Append objects in loop
// Create document after loop
// Write to file

Here's a small working example:

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QString>
#include <QDebug>
#include <map>

int main()
{
    const std::map<QString, QString> data
    {
        { "obj1", R"({ "id": 1, "info": { "type": 11, "code": 111 } })" },
        { "obj2", R"({ "id": 2, "info": { "type": 22, "code": 222 } })" }
    };

    QJsonObject jObj;
    for ( const auto& p : data )
    {
        jObj.insert( p.first, QJsonValue::fromVariant( p.second ) );
    }

    QJsonDocument doc { jObj };
    qDebug() << qPrintable( doc.toJson( QJsonDocument::Indented ) );

    return 0;
}

Output:

{
    "obj1": "{ \"id\": 1, \"info\": { \"type\": 11, \"code\": 111 } }",
    "obj2": "{ \"id\": 2, \"info\": { \"type\": 22, \"code\": 222 } }"
}