{"naviVector": {"endPoint": [7.4, 1844.25],"startPoint": [2.21, 2237.9]},"polygon": [[4.1, 7.2],[8.3, 1.4],],"ATC_type": 1,"ATC_id": 1111,"ATC_status": 1,} qt解析json
时间: 2023-07-07 15:23:31 浏览: 211
qt解析json
你可以使用QJsonDocument和QJsonObject来解析json数据,具体步骤如下:
1. 创建QJsonDocument对象,传入json字符串
```c++
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
```
2. 获取QJsonObject对象,用于访问json中的键值对
```c++
QJsonObject object = doc.object();
```
3. 获取需要的数据,可以使用value方法,传入键名获取对应的值,然后再转换为对应类型
```c++
QJsonArray polygonArray = object.value("polygon").toArray();
QVector<QPointF> polygonPoints;
for (int i = 0; i < polygonArray.size(); i++) {
QJsonObject pointObject = polygonArray[i].toObject();
qreal x = pointObject.value("x").toDouble();
qreal y = pointObject.value("y").toDouble();
polygonPoints.append(QPointF(x, y));
}
```
4. 注意:如果json字符串中存在不符合格式的键值对,或者键名不存在等情况,上述代码可能会抛出异常,需要进行错误处理。
完整代码如下:
```c++
QString jsonString = "{\"naviVector\": {\"endPoint\": [7.4, 1844.25],\"startPoint\": [2.21, 2237.9]},\"polygon\": [{\"x\": 4.1, \"y\": 7.2},{\"x\": 8.3, \"y\": 1.4}],\"ATC_type\": 1,\"ATC_id\": 1111,\"ATC_status\": 1}";
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
if (!doc.isObject()) {
qDebug() << "jsonString is not a json object!";
return;
}
QJsonObject object = doc.object();
QJsonArray polygonArray = object.value("polygon").toArray();
QVector<QPointF> polygonPoints;
for (int i = 0; i < polygonArray.size(); i++) {
QJsonObject pointObject = polygonArray[i].toObject();
qreal x = pointObject.value("x").toDouble();
qreal y = pointObject.value("y").toDouble();
polygonPoints.append(QPointF(x, y));
}
qDebug() << "polygon points:" << polygonPoints;
int type = object.value("ATC_type").toInt();
qDebug() << "ATC_type:" << type;
int id = object.value("ATC_id").toInt();
qDebug() << "ATC_id:" << id;
int status = object.value("ATC_status").toInt();
qDebug() << "ATC_status:" << status;
```
阅读全文