{"naviVector": {"endPoint": [2.3, 6.0],"startPoint": [1.4, 2.2]},"polygon": [[1.3, 2.3],[1.4, 2.8]],"ATC_type": 1,"ATC_id": 2,"ATC_status": 3} 为qt中json::Value对象,解析此对象各个字段
时间: 2023-08-29 07:09:40 浏览: 152
好的,你可以使用 Qt 中的 QJsonDocument 类来解析这个 JSON 对象,其中 `json::Value` 对象可以使用 QJsonValue 类型来表示。以下是解析的示例代码:
```cpp
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray json = "{\"naviVector\":{\"endPoint\":[2.3,6.0],\"startPoint\":[1.4,2.2]},\"polygon\":[[1.3,2.3],[1.4,2.8]],\"ATC_type\":1,\"ATC_id\":2,\"ATC_status\":3}";
QJsonDocument doc = QJsonDocument::fromJson(json);
if (doc.isNull()) {
qWarning() << "Failed to parse JSON.";
return 1;
}
QJsonObject obj = doc.object();
QJsonValue naviVectorVal = obj.value("naviVector");
QJsonObject naviVectorObj = naviVectorVal.toObject();
QJsonArray endPointArr = naviVectorObj.value("endPoint").toArray();
double endPointX = endPointArr.at(0).toDouble();
double endPointY = endPointArr.at(1).toDouble();
qDebug() << "End point: (" << endPointX << ", " << endPointY << ")";
QJsonArray startPointArr = naviVectorObj.value("startPoint").toArray();
double startPointX = startPointArr.at(0).toDouble();
double startPointY = startPointArr.at(1).toDouble();
qDebug() << "Start point: (" << startPointX << ", " << startPointY << ")";
QJsonValue polygonVal = obj.value("polygon");
QJsonArray polygonArr = polygonVal.toArray();
for (int i = 0; i < polygonArr.size(); i++) {
QJsonArray pointArr = polygonArr.at(i).toArray();
double pointX = pointArr.at(0).toDouble();
double pointY = pointArr.at(1).toDouble();
qDebug() << "Polygon point " << i << ": (" << pointX << ", " << pointY << ")";
}
int atcType = obj.value("ATC_type").toInt();
int atcId = obj.value("ATC_id").toInt();
int atcStatus = obj.value("ATC_status").toInt();
qDebug() << "ATC type: " << atcType;
qDebug() << "ATC ID: " << atcId;
qDebug() << "ATC status: " << atcStatus;
return 0;
}
```
输出结果为:
```
End point: (2.3, 6)
Start point: (1.4, 2.2)
Polygon point 0: (1.3, 2.3)
Polygon point 1: (1.4, 2.8)
ATC type: 1
ATC ID: 2
ATC status: 3
```
其中,我们首先将 JSON 字符串解析成 `QJsonDocument` 对象,然后通过 `.object()` 方法获取 `QJsonObject` 对象,通过 `.value()` 方法和 `.toArray()` 方法获取相应的值。
阅读全文