我正在尝试创建一个json文件,其中我只在一个QJsonArray中插入QjsonObjects,我得到的是每个QjsonObject都在一个独立的QJsonArray中,但我希望它们在同一个数组中。
每次单击保存按钮时都会调用此函数,这就是我的QJsonObjects的创建方式。
void List::insertDefect(const QString &parentDefect,const QString &defect,const QString &positions)const{
QString filename =createListDefect();
QFile file(filename);
file.open(QIODevice::Append | QIODevice::Text);
QJsonObject defectObject;
defectObject.insert("parentDefect", QJsonValue::fromVariant(parentDefect));
defectObject.insert("defect", QJsonValue::fromVariant(defect));
defectObject.insert("positions", QJsonValue::fromVariant(positions));
QJsonArray listArray;
listArray.push_back(defectObject);
QJsonDocument doc(listArray);
file.write(doc.toJson(QJsonDocument::Indented));}
以下是生成的json文件的示例:
[
{
"defect": "MISSING, DAMAGED",
"parentDefect": "SEAT BELTS",
"positions": "F | RB | "
}
]
[
{
"defect": "RIGIDITY,CORROSION,DISTORTION",
"parentDefect": "CHASSIS OR SUB-FRAME",
"positions": "B | RC | RB | "
}
]
我想让它看起来像这样:
[
{
"defect": "MISSING, DAMAGED",
"parentDefect": "SEAT BELTS",
"positions": "F | RB | "
},
{
"defect": "RIGIDITY,CORROSION,DISTORTION",
"parentDefect": "CHASSIS OR SUB-FRAME",
"positions": "B | RC | RB | "
}
]
答案 0 :(得分:1)
您在方法中创建QJsonArray listArray;
作为局部变量,因此每次调用该方法后都会销毁数组变量,并且每个对象都存储在单独的新数组中,您必须在方法外创建数组这样它就会在所有调用中持续存在,然后向其中添加对象并更新文档。
QJsonArray listArray;
void List::insertDefect()
....