我有一个包含航点的Json文件。该文件可以有更多或更少的录音。
{
"waypoint0": "10.05456, 51.02453, 0.0",
"waypoint1": "10.05456, 51.02453, 0.0",
"waypoint2": "10.05456, 51.02453, 0.0",
"waypoint3": "10.05456, 51.02453, 0.0",
"waypoint4": "10.05456, 51.02453, 0.0",
"waypoint5": "10.05456, 51.02453, 0.0",
"waypoint6": "10.05456, 51.02453, 0.0",
}
首先,我想阅读JSON文件: std :: vector route;
QString filename = QFileDialog::getOpenFileName(this,
tr("Flugweg laden"), "",
tr("Wegpunkt Datei (*.wpf)"));
QString val;
QFile file(filename);
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonObject it = d.object();
for(auto it = sett2.begin(); it != sett2.end(); ++it) {
//TODO
}
现在我想为每个对象执行代码,其中包含//TODO
的更改。
est::aladin::Waypoint waypoint0; // waypoint0 should be changed on the name of the values like in my JSON File. waypoint0 to waypoint6
waypoint0.id = 0; // waypoint0 меняется в соответствии кол-во запись на waypoint1 и далее.
waypoint0.displayed_number = -1; // the first waypoint should be have the number -1 and the last -2, waypoints beetween from 1 and till 98.
waypoint0.latitude_wgs84_radians = lat; //first value from waypoint0 - in this example - 10.05456 and etc.
waypoint0.longitude_wgs84_radians = long; //second value from waypoint0 - in this example - 51.02453 and etc.
waypoint0.altitude_wgs84_meters = alt; //third value from waypoint0 - in this example - 0.0 and etc.
waypoint0.type = est::aladin::WaypointType::GroundControlStation; // if it is waypoint0
//between the first and last waypoint WAYPOINT+NUMBER.type = est::aladin::WaypointType::FlyOver;
//Last waypoint WAYPOINT+NUMBER.type = est::aladin::WaypointType::Landing;
route.push_back(waypoint0); // waypoint0 should be changed on which waypoint we will push now.
如何解析JSON行"waypoint0": "10.05456, 51.02453, 0.0",
并输出到不同的变量。
答案 0 :(得分:0)
你的.json是不够的,我认为复制并粘贴它是错误的(最后一行中有一个不必要的逗号)。
我们必须做的第一件事是获取QJsonObject
,然后遍历其keys()
,结果是csv格式的字符串,所以我们必须将它与split分开,然后我们将每个项目转换为加倍toDouble()
。
QString filename = QFileDialog::getOpenFileName(this,
tr("Flugweg laden"), "",
tr("Wegpunkt Datei (*.wpf)"));
if(!filename.isEmpty()){
QByteArray val;
QFile file(filename);
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
QJsonDocument d = QJsonDocument::fromJson(val);
QJsonObject obj = d.object();
for(const QString &key: obj.keys() ){
QString line = obj[key].toString();
QStringList elements = line.split(",");
double lat= elements[0].toDouble();
double lng= elements[1].toDouble();
double alt= elements[2].toDouble();
qDebug()<<key<< lat<<lng<<alt;
est::aladin::Waypoint waypoint;
[...]
waypoint.latitude_wgs84_radians = lat;
waypoint.longitude_wgs84_radians = lng;
waypoint.altitude_wgs84_meters = alt;
[...]
route.push_back(waypoint);
}
}
注意:不要使用long作为变量的名称,因为它是保留名称。