【问题标题】:QJsonDocument to list or array in c++QJsonDocument 在 C++ 中列出或数组
【发布时间】:2017-11-16 05:43:28
【问题描述】:

我已经尝试过这段代码并且工作正常,但我不明白如何使用 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 获取(来自 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" :'测试'}]

我需要获取 json 并在列表或数组中设置。 我的目标是使用 c++ 和 Qt 将 json 响应转换为数组或列表。 有什么想法吗?

谢谢

【问题讨论】:

  • 您的 JSON 响应是一个数组。数组的每个元素都有四个带有字符串值的 JSON 对象:“MCC_Dealer”、“MCC_User”、“CurrentDealer”、“CurrentUser”。请澄清一下,您希望如何将它们存储在列表中。
  • 每一行都是一个对象,我想把它放在一个对象列表中,比如List obj = new List ();和 obj.add(line1);等等等等..我来自c#,但我想在c ++中做到这一点
  • 好吧,但是您已经有一个 QJsonArray 来存储每个提到的对象。为什么需要另一个结构(列表)来存储它们?如果你写QJsonArray jsonArray = jsonResponse.array();,你会得到你需要的,我想。
  • 工作!从第一个元素调用属性,我执行 jsonArray[0]['MCC_Dealer'] ?

标签: c++ arrays json list qt


【解决方案1】:

正如我在 cmets 中提到的,您的 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();
    }
}

【讨论】:

  • 正确答案!可以直接调用一种属性吗?例如,如果我调用 jsonArray[0].key("MCC_Dealer")?或类似的。?
  • 我认为是的,但方式不同:jsonArray[0].toObject().find("MCC_Dealer").key() 左右。但我不建议这样做,因为这样你就不会检查每个函数调用返回的值的正确性,并且在某些情况下可能会失败。
  • 调用properties的解决方法是:convert in object, QJsonObject temp = jsonarray[n].toObject();在你调用 temp.value("yourvalue").toString(); - 这行得通。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多