【问题标题】:How I can add more than one QJsonObject to a QJsonDocument - Qt如何将多个 QJsonObject 添加到 QJsonDocument - Qt
【发布时间】:2019-03-16 06:03:50
【问题描述】:

我想将多个 QJsonObject 而不是 QJsonArray 添加到 QJsonDocument。这可能吗?它应该是这样的:

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

我已经推荐了this,但我不想使用JsonArray。只想使用 JsonObject 。我也在这里参考了更多答案,但找不到任何解决方案。

我试过这个:

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

【问题讨论】:

  • 你的popData函数是如何实现的?你能写一个 MCVE 来构造这样一个畸形的QJsonDocument吗?
  • 我将QJsonObject 作为popData() 函数中的引用传递并获取包含"Obj1" : { "objID": "111", "C1" : { "Name":"Test1", "Enable" : true } } 一个对象的填充对象。

标签: c++ json qt qjson qjsonobject


【解决方案1】:

在循环中,每次迭代都会创建一个新的 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 } }"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2019-06-18
    • 1970-01-01
    相关资源
    最近更新 更多