我正在编写几个测试函数,因为这是我第一次使用Qt并尝试理解开发我的最终项目所需的部分。以下是功能:
#include "money.h"
#include "ui_money.h"
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QString>
#include <QJsonArray>
#include <QJsonDocument>
Money::Money(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Money)
{
ui->setupUi(this);
}
Money::~Money()
{
delete ui;
}
void Money::on_getJsonData_clicked()
{
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://scarjamoney.no-ip.biz")));
}
void Money::replyFinished(QNetworkReply* Reply)
{
QString string = Reply->readAll();
QJsonDocument document = QJsonDocument::fromJson(string.toUtf8());
if(document.isArray()){
QJsonArray valuesA = document.array();
foreach (const QJsonValue write, valuesA){
//ui->textEdit->setText("dentro");
QString text = QString::number(write.toDouble());
//qDebug() << "ciao" << text;
ui->textEdit->append(text);
}
}
else if(document.isObject()){
QJsonObject valuesO = document.object();
foreach (const QJsonValue write, valuesO){
ui->textEdit->append("inside");
}
ui->textEdit->append("it's an object");
}
}
如果以数组形式测试json回复,例如:
[1,2]
一切正常,而不是测试对象,如:
{"firstValue":1,"secondValue":2}
我收到以下错误编译:
C:\Qt\Tools\QtCreator\bin\Money\money.cpp:53: error: variable 'QJsonObject valuesO' has initializer but incomplete type
QJsonObject valuesO = document.object();
C:\Qt\Tools\QtCreator\bin\Money\money.cpp:53: error: invalid use of incomplete type 'class QJsonObject'
QJsonObject valuesO = document.object();
为什么不将我的测试json文档转换为对象?
提前致谢, 詹姆斯
答案 0 :(得分:9)
您忘了加入QJsonObject
:
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonObject>