【问题标题】:Why can't I parse the Cryptsy JSON API with Qt5/C++?为什么我不能用 Qt5/C++ 解析 Cryptsy JSON API?
【发布时间】:2015-03-04 08:04:08
【问题描述】:

我正在尝试使用 Qt5 解析 this JSON Web-API,并使用 QJsonDocument 和 QJsonObject 解析 here。但我无法访问 QJsonObject 的 JSON 值。

这是我迄今为止尝试过的:

// Contains the whole API as QString...
QString data = QString(reply->readAll());
// Reads the JSON as QJsonDocument...
QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
// Reads the JSON as QJsonObject...
QJsonObject jsonObject = jsonResponse.object();

现在我已经准备好我的对象,但是尝试访问 JSON 的值却以某种方式失败了:

// This returns an empty string ""!?!
qDebug() << jsonObject.value("success").toString();

好吧,也许我把钥匙弄错了:

// Let's check the keys...
QStringList stringList = jsonObject.keys();
for (QStringList::Iterator it = stringList.begin(); it != stringList.end(); ++it)
{
    // This returns "success" and "return" - huh!?!
    qDebug() << *it;
}

好的,按键非常好,为什么不工作?

// Let's check the values by using the keys directly...
for (QStringList::Iterator it = stringList.begin(); it != stringList.end(); ++it)
{
    // This returns empty strings "" and "" - now what?!?
    qDebug() << jsonObject.value(*it).toString();
}

这又是没有意义的。我不明白为什么我不能通过键访问 JSON 对象的值。有什么想法吗?

我在其他 JSON API(例如 this one)上尝试了完全相同的代码,没有任何问题。我完全被困在这里了。

【问题讨论】:

    标签: c++ json parsing qt5 key-value


    【解决方案1】:

    这是我的 Qt5 Json 解析 Cryptsy API 的解决方案。

    QEventLoop loopEvent;
    QNetworkAccessManager namMNGR;
    QObject::connect(&namMNGR, SIGNAL(finished(QNetworkReply*)), &loopEvent, SLOT(quit()));
    QNetworkRequest req(QUrl(QString("http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=%1").arg(marketID)));
    QNetworkReply *reply = namMNGR.get(req);
    loopEvent.exec();
    //Json API parsing begins.
    QString jsonSTR = reply->readAll();
    if (!(reply->error() == QNetworkReply::NoError)) {
        delete reply; //API Connection Problem.
    }
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonSTR.toUtf8());
    QJsonObject obj1 = jsonDocument.object();
    QJsonValue val1 = obj1.value(obj1.keys().first());
    QJsonObject obj2 = val1.toObject();
    QJsonValue val2 = obj2.value(obj2.keys().first());
    QJsonObject obj3 = val2.toObject();
    QJsonValue marketDataValue = obj3.value(obj3.keys().first());
    QJsonObject marketDataObject = marketDataValue.toObject();
    QJsonArray sellordersArray = marketDataObject["sellorders"].toArray();
    

    您是否设法从 Qt5 获取经过身份验证的 POST API 数据?我正在尝试弄清楚如何做到这一点。

    【讨论】:

      猜你喜欢
      • 2012-10-02
      • 2017-10-02
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 2018-11-27
      • 2016-12-23
      相关资源
      最近更新 更多