我已经尝试过这段代码并且有效,但我不明白如何获取 json 并使用 Qt 转换为数组或列表。 我的代码:
QEventLoop eventLoop;
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
QNetworkRequest req(QUrl(QString("http://myurljson.com/getjson")));
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // blocks stack until "finished()" has been called
if (reply->error() == QNetworkReply::NoError) {
QString strReply = (QString)reply->readAll();
qDebug() << "Response:" << strReply;
QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject jsonObj = jsonResponse.object();
qDebug() << "test:" << jsonObj["MCC_Dealer"].toString();
qDebug() << "test1:" << jsonObj["MCC_User"].toString();
delete reply;
}
else {
//failure
qDebug() << "Failure" <<reply->errorString();
delete reply;
}
我的 json 获取(来自 url 的 3 条记录):
[{"MCC_Dealer":'test',"MCC_User":'test',"CurrentDealer":'test',"CurrentUser":'test'},{"MCC_Dealer":'test',"MCC_User":'test',"CurrentDealer":'test',"CurrentUser":'test'},{"MCC_Dealer":'test',"MCC_User":'test',"CurrentDealer":'test',"CurrentUser":'test'}]
我需要获取 json 并在列表或数组中设置。 我的目标是用 c++ 和 Qt 转换数组或列表中的 json 响应。 有什么想法吗?
谢谢
最佳答案
正如我在评论中提到的,您的 JSON 响应已经是一个数组,因此您无需创建额外的结构来存储您获得的数据。为了反序列化您的数据,您可以执行以下操作:
[..]
QJsonArray jsonArray = jsonResponse.array();
for (auto it = jsonArray.constBegin(); it != jsonArray.constEnd(); ++it)
{
const QJsonValue &val = *it;
// We expect that array contains objects like:
// {"MCC_Dealer":'test',"MCC_User":'test',"CurrentDealer":'test',"CurrentUser":'test'}
QJsonObject o = val.toObject();
// Iterate over all sub-objects. They all have string values.
for (auto oIt = o.constBegin(); oIt != o.constEnd(); ++oIt)
{
// "MCC_Dealer":'test'
qDebug() << "Key:" << oIt.key() << ", Value:" << oIt.value().toString();
}
}
关于c++ - QJsonDocument 在 C++ 中列出或排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44538549/