我对Qt很陌生。开始研究如何绕过HTML5移动应用程序的限制。我试图在Qt中解析JSON数据。这个想法是,应用程序将使用SQLite的离线模式,并连接到一个API时,在线。我在网上找到了一个指南,但它似乎不适用于我的API。
#include <QCoreApplication>
#include <QDebug>
#include <QApplication>
#include <QtWebKitWidgets/QWebFrame>
#include <QtWebKitWidgets/QWebPage>
#include <QtWebKitWidgets/QWebView>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QWebSettings>
#include <QVariant>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <QJsonArray>
void sendRequest();
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
sendRequest();
return a.exec();
}
void sendRequest() {
// create custom temporary event loop on stack
QEventLoop eventLoop;
// "quit()" the event-loop, when the network request "finished()"
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
// the HTTP request
QNetworkRequest req( QUrl( QString("http://127.0.0.1:8000/api/v1") ) );
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // blocks stack until "finished()" has been called
if (reply->error() == QNetworkReply::NoError) {
QString strReply = (QString)reply->readAll();
//parse json
qDebug() << "Response:" << strReply;
QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject jsonObj = jsonResponse.object();
qDebug() << "username:" << jsonObj["username"].toString();
qDebug() << "password:" << jsonObj["password"].toString();
delete reply;
}
else {
//failure
qDebug() << "Failure" <<reply->errorString();
delete reply;
}
}API接口
[
{
"id": 1,
"username": "admin",
"password": "qwerty"
},
{
"id": 2,
"username": "chris",
"password": "1234"
}
]得到的结果是:
Response: ""
username: ""
password: ""发布于 2015-02-13 12:53:34
基于strReply的值(它是一个空的QString ),我认为JSON解析与您的问题没有任何关系。readAll ()的文档说明:
此函数无法报告错误;返回空的QByteArray()可能意味着当前没有可读取的数据,或者发生了错误。
这看起来就像这里发生的事。您的代码应该可以工作,但我会再次检查URL http://127.0.0.1:8000/api/v1。我不知道它是什么样的API,但是它返回您粘贴的JSON却没有在URL中提供一些额外的参数,这看起来很奇怪。
编辑
您的API返回一个JSON数组,但是您正在像处理对象一样处理它。不要使用QJsonObject jsonObj = jsonResponse.object();,而是尝试:
QJsonArray json_array = jsonResponse.array();
foreach (const QJsonValue &value, json_array) {
QJsonObject json_obj = value.toObject();
qDebug() << json_obj["username"].toString();
qDebug() << json_obj["password"].toString();
}https://stackoverflow.com/questions/28499619
复制相似问题