我有一个要在 UI 上读取和显示的 Json 文件。阅读很好,但是当我尝试更新值轴距时,代码运行没有错误,但它没有更新 Json
Json 文件示例
{
"$type": "SystemList",
"$values": [
{
"chassicId": 1000,
"wheelbase": 98
},
{
"chassicId": 1001,
"wheelbase": 102
}
]
}
这是写函数。我尝试将 Json 文件解析为 QJsonArray,然后使用函数 id 参数进行迭代和映射以更新轴距值。
void updateWheelbase(const int& id)
{
updatedWheelbase = dialog.wheelbaseInput().toDouble();
QFile file("json file path");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray jsonData = file.readAll();
file.close();
QJsonDocument itemDoc = QJsonDocument::fromJson(jsonData);
QJsonObject rootObject = itemDoc.object();
QJsonArray valuesArray = rootObject.value("$values").toArray();
//get a copy of the QJsonObject
QJsonObject obj;
for (auto v: valuesArray) {
QJsonObject o = v.toObject();
if (o.value("chassicId").toInt() == id) {
obj = o;
break;
}
}
// modify the object
obj["wheelbase"] = updatedWheelbase;
int position = 0;
// erase the old instance of the object
for (auto it = valuesArray.begin(); it != valuesArray.end(); ++it) {
QJsonObject obj = (*it).toObject();
if (obj.value("chassicId").toInt() == id) {
valuesArray.erase(it);
//assign the array copy which has the object deleted
rootObject["$value"] = valuesArray;
break;
}
position++;
}
// add the modified QJsonObject
valuesArray.append(obj);
// replace the original array with the array containing our modified threshold object
itemDoc.setObject(rootObject);
file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
file.write(itemDoc.toJson());
file.close();
}