我已经尝试过这段代码并且有效,但我不明白如何使用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条记录):
[{&#34; MCC_Dealer&#34;:&#39;测试&#39;&#34; MCC_User&#34;:&#39;测试&#39;&#34; CurrentDealer&#34 ;: &#39;测试&#39;&#34; CurrentUser&#34;:&#39;测试&#39;},{&#34; MCC_Dealer&#34;:&#39;测试&#39;&#34 ; MCC_User&#34;:&#39;测试&#39;&#34; CurrentDealer&#34;:&#39;测试&#39;&#34; CurrentUser&#34;:&#39;测试&#39; },{&#34; MCC_Dealer&#34;:&#39;测试&#39;&#34; MCC_User&#34;:&#39;测试&#39;&#34; CurrentDealer&#34;:&# 39;测试&#39;&#34; CurrentUser&#34;:&#39;测试&#39;}]
我需要获取json并在列表或数组中设置。 我的目标是用c ++和Qt转换数组或列表中的json响应。 有什么想法吗?
由于
答案 0 :(得分:2)
正如我在评论中提到的,您的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();
}
}