如何将多个QJSonObject添加到qjSondocument -qt
How I can add more than one QJsonObject to a QJsonDocument - Qt
我想在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 } }"
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 将QIcon添加到QTableView单元格
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 将图像添加到资源文件夹UWP C++
- 如何将多个QJSonObject添加到qjSondocument -qt