如何将多个QJSonObject添加到qjSondocument -qt

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

本文关键字:添加 qjSondocument -qt QJSonObject      更新时间:2023-10-16

我想在qjsondocument中添加多个qjsonobject而不是qjsonarray。这可能吗?看起来应该这样:

{
    "Obj1" : {
        "objID": "111",
        "C1" : {
            "Name":"Test1",
            "Enable" : true
        }
    },
    "Obj2" : {
        "objID": "222",
        "C2" : {
            "Name":"Test2",
            "Enable" : true
        }
    }
}

我已经提到了这个,但我不想使用JsonArray。只想使用JsonObject。我还在这里提到了更多答案,但是DINT找到了任何解决方案。

我尝试了:

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();

输出

{
    "Obj1" : {
        "objID": "111",
        "C1" : {
            "Name":"Test1",
            "Enable" : true
        }
    }
}
{
    "Obj2" : {
        "objID": "222",
        "C2" : {
            "Name":"Test2",
            "Enable" : true
        }
    }
}

在循环中,每次迭代都在创建一个新的JSON文档并将其写入流。这意味着它们都是多个独立文档。您需要创建一个QJsonObject(父对象),并用其他所有对象作为其中的一部分填充它。然后,您只有一个对象,在循环之后,您可以创建一个QJsonDocument并将其写入文件。

这是您的代码,可以在每次迭代中创建一个新文档:

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

这是您需要做的:

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

这是一个小工作示例

#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;
}

输出

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