如何将对象添加到Json文件

时间:2019-03-28 10:30:59

标签: c++ json qt

我正在尝试将3个传感器的数据记录到json文件中。我要做的就是将Speed,Latitude和Longitude写入Json文件,并使用一个包含上述内容的对象。这是一个json文件,其中包含一个路由对象,n个子对象每个都包含速度,纬度和经度。

我从3个全局QList列表中获得了这3个值。以下是本地存储的json文件。 (双精度值不是实际值,仅用于测试目的)

 {
"Sensordata": [
 {
   "Speed": 1,
   "GPSLat":-12.5687,
   "GPSLong":26.125546

 },
 {
  "Speed": 1,
  "GPSLat":-12.5687,
  "GPSLong":26.125546
}
]
}

这是json的外观,添加时必须以相同的方式格式化

void MainWindow::save_to_json()  {
QFile file_obj(".../SensorData.json");
if(!file_obj.open(QIODevice::ReadOnly)){
    qDebug()<<"Failed to open "<<"SensorData.json";
    exit(1);
}


QTextStream file_text(&file_obj);
QString json_string;
json_string = file_text.readAll();
file_obj.close();
QByteArray data_json = json_string.toLocal8Bit();
QJsonDocument doc = QJsonDocument::fromJson(data_json);

QJsonObject rootObj = doc.object();
QJsonValue SensorData = rootObj.value("SensorData");

if(!SensorData.isArray())
{
    // array expected - handle error
}

QJsonArray SensorDataArray = SensorData.toArray();

QJsonObject newObject;
newObject["Speed"] = speed_array.takeFirst();
newObject["GPSLat"] = gps_lat.takeFirst();
newObject["GPSLong"] = gps_long.takeFirst();

SensorDataArray.push_back(newObject);


}

ASSERT: "!isEmpty()" in file /home/username/Qt/5.12.1/gcc_64/include        /QtCore/qlist.h, line 347
11:32:55: The program has unexpectedly finished.
11:32:55: The process was ended forcefully.

这是上面的代码创建的错误。

1 个答案:

答案 0 :(得分:0)

要修改数据,以您的示例为例,您需要检查QJsonDocument中包含的数据是数组还是简单对象。对于您的情况,我想您想将数据追加到数组中。尝试这样的事情:

// Read the data
const QString filename = "example.json";
QJsonDocument doc = read(filename);

// Check that it's an array and append new data
QJsonValue sensorData = doc.value("SensorData");
if (!sensorData.isArray()) {
    // if the doc is empty you may want to create it
} 

// Get the array and insert the data
auto array = sensorData.array();
array.append(QJsonObject{
    {"Speed", speed_array.takeFirst()},
    {"GPSLat", gps_lat.takeFirst()},
    {"GPSLong",gps_long.takeFirst(),
});

// Restore your sensor data
doc.setObject(QJsonObject{{"SensorData", array}});

// Write the new data
write(filename, doc); 

用于读取/写入JSON文档的帮助程序功能可以避免打开/关闭文件的错误:

QJsonDocument read(const QString& filename) {
    QFile file(filename);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    const QString val = file.readAll();
    file.close();
    return QJsonDocument::fromJson(val.toUtf8());
}

void write(const QString& filename, const QJsonDocument& document) {
    QFile file(filename);
    file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
    file.write(document.toJson());
    file.close();
}

更新

要不覆盖原始文档,必须更新根对象的字段或使用QJsonValueRef

// Get a reference to your array 
QJsonObject root = doc.object();
QJsonValueRef ref = root.find("SensorData").value();

// get the array and insert the data
QJsonArray array = ref.toArray();
array.append(QJsonObject{
    {"Speed", speed_array.takeFirst()},
    {"GPSLat", gps_lat.takeFirst()},
    {"GPSLong",gps_long.takeFirst(),
});

// Update the ref with the new data
ref = array

// update the modified data in the json document
doc.setObject(root);