如何将多个QJsonObject添加到QJsonDocument-Qt
我想向QJsonDocument添加多个QJsonObject而不是QJsonArray.这可能吗?它应该看起来像这样:
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
}
}
}
我已引用此,但我不想使用JsonArray
.只想使用JsonObject
.我还在这里引用了更多答案,但没有找到任何解决方案.
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.
我尝试过这个:
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
并将其用于写入文件.
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
// ...
}
这是您需要做的:
// 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 } }"
}