QJson要在c++中列出或数组的文档



我尝试过这段代码并能正常工作,但我不明白如何使用Qt获取json并在数组或列表中进行转换。我的代码:

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-get(来自url的3条记录):

[{"MCC_Daler":'test',"MCC_User":'test',"CurrentDealer":'est',"Current User":'test'},{"MC_Daler":'test],"MCC_User":'test',"CurrentDealer":'est',"Current User":'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();
}
}

最新更新