c++ - 为什么我不能用 Qt5/C++ 解析 Cryptsy JSON API?

标签 c++ json parsing qt5 key-value

我正在尝试解析 this JSON Web-API 使用 Qt5 和 C++ 使用 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();

嗯,也许我把 key 弄错了:

// 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 之一)上尝试了完全相同的代码,没有任何问题。我完全被困在这里。

最佳答案

这是我的 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 数据?我正在尝试弄清楚该怎么做。

关于c++ - 为什么我不能用 Qt5/C++ 解析 Cryptsy JSON API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537907/

相关文章:

windows - 在c/c++中使用检查函数编译Windows NT命令行代码循环

c++ - 将不可复制的闭包对象传递给 std::function 参数

java - 如何限制将 json 映射到 jpa 对象或从 jpa 对象映射的工作

python - 在Python中延迟解析有状态的、每记录多行的数据流?

c - 如何解析结构体数组作为参数?

c++ - 在 Node.js C++ 插件中,永远不会调用 SetWindowsHookEx 的回调

c++ - 我可以在 mac 命令行应用程序与 mac 应用程序之间进行通信吗

javascript - 对 JSON 数组进行排序并使用 $.each 进行回显

java - 如何使用 Spring Data REST 存储库创建和连接相关资源?

javascript - 将 CSS 结构解析为对象