コード例 #1
0
QJsonObject SeleniumServerHub::post(QString url, QJsonObject rawBody)
{
    QJsonDocument doc;
    doc.setObject(rawBody);

    return exec(url, doc.toJson(), POST);
}
コード例 #2
0
ファイル: jsonhelper.cpp プロジェクト: RostaTasha/xpiks
    void mergeJson(const QJsonDocument &mergeFrom, QJsonDocument &mergeTo, bool overwrite, CompareValuesJson &comparer) {
        if (mergeFrom.isNull()) {
            LOG_WARNING << "attempted to merge with Null json document";
            return;
        }

        if (overwrite || mergeTo.isNull()) {
            LOG_DEBUG << "Overwriting the document";
            mergeTo = mergeFrom;
        } else {
            if (mergeFrom.isArray()) {
                QJsonArray arrayFrom = mergeFrom.array();
                QJsonArray arrayTo = mergeTo.array();

                if (mergeJsonArrays(arrayFrom, arrayTo, comparer)) {
                    mergeTo.setArray(arrayTo);
                }
            } else {
                QJsonObject objectFrom = mergeFrom.object();
                QJsonObject objectTo = mergeTo.object();

                if (mergeJsonObjects(objectFrom, objectTo, comparer)) {
                    mergeTo.setObject(objectTo);
                }
            }
        }
    }
コード例 #3
0
void QDiscordWsComponent::login(const QString& token,
								QDiscordTokenType tokenType)
{
	if(_reconnectTimer.isActive())
		_reconnectTimer.stop();
	QJsonDocument document;
	QJsonObject mainObject;
	mainObject["op"] = 2;
	QJsonObject dataObject;
	dataObject["token"] =
			QDiscordUtilities::convertTokenToType(token, tokenType);
	dataObject["v"] = 5;
	dataObject["properties"] =
			QJsonObject({
							{"$os", QSysInfo::kernelType()},
							{"$browser", QDiscordUtilities::libName},
							{"$device", QDiscordUtilities::libName},
							{"$referrer", "https://discordapp.com/@me"},
							{"$referring_domain", "discordapp.com"}
						});
	dataObject["large_threshold"] = 100;
	dataObject["compress"] = false;
	mainObject["d"] = dataObject;
	document.setObject(mainObject);
	_socket.sendTextMessage(document.toJson(QJsonDocument::Compact));
}
コード例 #4
0
ファイル: loginworker.cpp プロジェクト: illogica/Hca
void LoginWorker::doWork(HcaThread *t)
{
    QElapsedTimer totalTime;
    totalTime.start();

    m_id = t->id();
    DbManager* dbm = t->dbManager();
    emit(t->setThreadStatus(m_id, false)); //this must always be the first

    QScopedPointer<Client> c(new Client(this));

    if(!dbm->findUserByUuid(uuid, c.data())){
        qWarning() << "User not found, creating...";
        dbm->createUser(c.data());
    }

    c->setStatus(ONLINE);
    dbm->updateClient(c.data());

    QJsonObject response = c->toFullJsonObject();
    response[REQUEST] = LOGIN;
    QJsonDocument doc;
    doc.setObject(response);
    qWarning() << "Emitting login from " << QThread::currentThreadId();
    emit loginResult(doc.toJson(QJsonDocument::Compact), socket, c->id());
    emit(t->setThreadStatus(m_id, true)); //this must always be the last
    qWarning() << "loginRequest evaded in " << totalTime.elapsed() << "ms";
}
コード例 #5
0
ファイル: TradeTable.cpp プロジェクト: RobertHu/QtUiDemo
bool TradeTable::SaveColumnJson()
{
	int count = m_ColumnMap.count();
	QJsonArray jsonArray;
	for(int i=0;i<count;i++)
	{
		QJsonObject jsonObject;
		jsonObject.insert("columnText",m_ColumnMap[i].GetColumnText());
		jsonObject.insert("isShow",m_ColumnMap[i].IsShow());
		jsonObject.insert("isForbidHide",m_ColumnMap[i].IsForbidHide());
		jsonObject.insert("isPicture",m_ColumnMap[i].IsPicture());
		jsonArray.append(jsonObject);
	}
	QJsonObject root;
	root.insert("columnSetting",jsonArray);
	QFile file(m_ColumnJsonFile);
	if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
		return false;
	QTextStream stream(&file);
	QJsonDocument jsonDoc;
	jsonDoc.setObject(root);
	stream << jsonDoc.toJson();
	file.close();

	return true;
}
コード例 #6
0
void QDiscordWsComponent::setStatus(bool idle, QDiscordGame game)
{
	if(_token == "")
		return;
	if(_gateway == "")
		return;
	QJsonDocument document;
	QJsonObject object;
	object["op"] = 3;
	QJsonObject presenceObject;
	presenceObject["idle_since"] = idle ?
				QDateTime::currentMSecsSinceEpoch() : QJsonValue();
	if(game.name() != "")
	{
		QJsonObject gameObject;
		gameObject["name"] = game.name();
		gameObject["url"] = game.url()==""?QJsonValue():game.url();
		gameObject["type"] = static_cast<int>(game.type());
		presenceObject["game"] = gameObject;
	}
	else
		presenceObject["game"] = QJsonValue();
	object["d"] = presenceObject;
	document.setObject(object);
	_socket.sendTextMessage(document.toJson(QJsonDocument::Compact));
}
コード例 #7
0
ファイル: option.cpp プロジェクト: JuUsT/bloodstreamchallenge
bool Option::saveOption()
{
    QJsonDocument jsonDocument;

    QJsonObject jsonSingleValue;
    jsonSingleValue.insert("fullscreen",QJsonValue(this->isFullscreen()));
    jsonSingleValue.insert("volume",QJsonValue(this->getVolume()));
    jsonSingleValue.insert("mute",QJsonValue(this->isMute()));

    if(this->language==Option::french)
        jsonSingleValue.insert("language",QJsonValue(QString("french")));
    else if(this->getLanguage()==Option::english)
        jsonSingleValue.insert("language",QJsonValue(QString("english")));
    else
        jsonSingleValue.insert("language",QJsonValue(QString("english")));


    jsonDocument.setObject(jsonSingleValue);

    fileOption = new QFile(this->jsonFilename);
    if(fileOption->open(QIODevice::WriteOnly))
    {
        QTextStream fileStream(fileOption);
        fileStream << jsonDocument.toJson();

        fileOption->close();
        return true;
    }
    else
    {
        fileOption->close();

        return false;
    }
}
コード例 #8
0
ファイル: collectmailsesb.cpp プロジェクト: privet56/qWebTest
void collectmailsesb::__testjson()
{
    QJsonDocument doc;
    QJsonObject data;
    data.insert("data", QJsonValue(QJsonObject()));
    {
        //QJsonObject esb;
        //esb.insert("[ESB]", QJsonValue(QJsonArray()));

        QJsonArray a;
        a.append(QJsonValue(QString("ae")));
        data.insert("data2", QJsonValue(a));

        QJsonArray aa = data.value("data2").toArray();
        aa.append(QJsonValue(QString("aee")));
        data.remove("data2");
        data.insert("data2", QJsonValue(aa));

        //doc.object().value("data").toObject().insert("[ESB]", QJsonValue(a));
        //QJsonObject data2;
        //data2.insert("data2", QJsonValue(QJsonObject()));

        //data.insert("data2", QJsonValue(QString("val2")));
    }
    doc.setObject(data);

    QMessageBox::warning(0, "__testjson", doc.toJson());

    /*
    QFile file("c:/temp/test.json");
    file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
    file.write(doc.toJson());
    file.close();
    */
}
コード例 #9
0
ファイル: MySqlStorage.cpp プロジェクト: tatiotir/QJabberd
bool MySqlStorage::addContactToRoster(QString jid, Contact contact)
{
    if (contactExists(jid, contact.getJid()))
    {
        updateNameToContact(jid, contact.getJid(), contact.getName());
        updateGroupToContact(jid, contact.getJid(), contact.getGroups());
        return true;
    }
    else
    {
        if (userExists(contact.getJid()))
        {
            QJsonDocument document;
            QJsonObject object;
            object.insert("groups", QJsonArray::fromStringList(QStringList::fromSet(contact.getGroups())));
            document.setObject(object);

            QSqlQuery query;
            query.prepare("INSERT INTO qjabberd_contact(user_id, approved, ask, groups, jid, name, subscription, version)"
                          " VALUES(:user_id, :approved, :ask, :groups, :jid, :name, :subscription, :version)");
            query.bindValue(":user_id", getUserId(jid));
            query.bindValue(":version", contact.getVersion());
            query.bindValue(":approved", (int)contact.getApproved());
            query.bindValue(":ask", contact.getAsk());
            query.bindValue(":jid", contact.getJid());
            query.bindValue(":name", contact.getName());
            query.bindValue(":subscription", contact.getSubscription());
            query.bindValue(":groups", document.toJson());
            return query.exec();
        }
    }
    return false;
}
コード例 #10
0
ファイル: MySqlStorage.cpp プロジェクト: tatiotir/QJabberd
bool MySqlStorage::addItemsToPrivacyList(QString jid, QString privacyListName, QList<PrivacyListItem> items)
{
    int user_id = getUserId(jid);

    m_database.transaction();

    QJsonDocument document;
    QJsonObject object;
    foreach (PrivacyListItem item, items)
    {
        object.insert("childs", QJsonArray::fromStringList(QStringList::fromSet(item.getChildsElement())));
        document.setObject(object);

        QSqlQuery query;
        query.prepare("INSERT INTO qjabberd_privacylist(user_id, ptype, pvalue, action, iorder, child, privacyListName)"
                      " VALUES(:user_id, :ptype, :pvalue, :action, :iorder, :child, :privacyListName)");
        query.bindValue(":user_id", user_id);
        query.bindValue(":ptype", item.getType());
        query.bindValue(":pvalue", item.getValue());
        query.bindValue(":action", item.getAction());
        query.bindValue(":iorder", item.getOrder());
        query.bindValue(":child", document.toJson());
        query.bindValue(":privacyListName", privacyListName);
        query.exec();
    }
コード例 #11
0
JsonRPCRequest* JsonRPCCommunicator::sendRequest(const QString& pMethod, const QJsonObject& pParams, bool pDaemonHttp)
{

    QUrl lUrl = endpoint_uri;
    QJsonObject lJsonRoot;

    /* Depending of RPC type, will append method name in URI or in JSON data */
    if ( pDaemonHttp ) {
        lJsonRoot = pParams;
        lUrl.setPath("/"+pMethod);
    }
    else {
        lJsonRoot.insert("jsonrpc",QJsonValue::fromVariant(rpc_version));
        lJsonRoot.insert("method",QJsonValue::fromVariant(pMethod));
        if ( !pParams.empty() ) {
            lJsonRoot.insert("params", pParams);
        }
    }

    QJsonDocument lJsonDoc;
    lJsonDoc.setObject(lJsonRoot);

    QNetworkRequest lReq(lUrl);
    lReq.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");

    JsonRPCRequest* lJsonReq = new JsonRPCRequest(pParams, pDaemonHttp);
    QNetworkReply* lReply = network_access_mgr.post(lReq, lJsonDoc.toJson());

    QObject::connect(lReply, SIGNAL(finished()), lJsonReq, SLOT(onRequestFinished()));
    QObject::connect(lReply, SIGNAL(error(QNetworkReply::NetworkError)), lJsonReq, SLOT(onRequestError(QNetworkReply::NetworkError)));


    return lJsonReq;

}
コード例 #12
0
ファイル: mainwindow.cpp プロジェクト: obiwankennedy/rmindmap
void MainWindow::saveMindMap()
{

    if (m_currentMindMapPath.isNull())
    {
            saveAsMindMap();
    }

    if(!m_currentMindMapPath.endsWith(".rmap"))
    {
         m_currentMindMapPath += ".rmap";
    }
    QFile file(m_currentMindMapPath);


    QFileInfo fileinfo(file);
    m_preferences->registerValue("MindMapDirectory",fileinfo.absoluteDir().canonicalPath());

    QJsonDocument doc;
    QJsonObject root;
    //m_stringManager->writeToData(root);
    m_scene->writeToData(root);

    doc.setObject(root);


    //QFile file(m_currentMindMapPath);
    if (file.open(QIODevice::WriteOnly))
    {
        QFileInfo fileinfo(file);
        m_preferences->registerValue("MindMapDirectory",fileinfo.absoluteDir().canonicalPath());
        file.write(doc.toJson());
        file.close();
    }
}
コード例 #13
0
ファイル: putpolicy.cpp プロジェクト: xiaojianwu/QtQiNiuSDK
QString PutPolicy::token(QString ak, QString sk, QString scope)
{

	QJsonDocument doc;

	QJsonObject obj;

	// 	指定上传的目标资源空间(Bucket) 和资源键(Key) 。
	// 		有两种格式:
	// 		● <bucket>,表示允许用户上传文件到指定的 bucket。在这种格式下文件只能“新增”,若已存在同名资源上传则会失败。
	// 		● <bucket> : <key>,表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”,
	// 若已存在同名资源则会被覆盖。如果只希望上传指定key的文件,并且不允许修改,那么可以将下面的 insertOnly 属性值设为1	
	obj["scope"] = scope;

	// 文件在多少天后被删除,七牛将文件上传时间与指定的deleteAfterDays天数相加,
	// 得到的时间入到后一天的午夜(CST, 中国标准时间),从而得到文件删除开始时间。
	//例如文件在2015年1月1日上午10:00 CST上传,指定deleteAfterDays为3天,那么会在2015年1月5日00 : 00 CST之后当天内删除文件。
	obj["deleteAfterDays"] = 7;

	// 限定为“新增”语意。
	// 如果设置为非0值,则无论scope设置为什么形式,仅能以“新增”模式上传文件。
	obj["insertOnly"] = 0;

	// 上传凭证有效截止时间。
	// Unix时间戳,单位:秒。该截止时间为上传完成后,在七牛空间生成文件的校验时间,而非上传的开始时间,
	// 一般建议设置为“上传开始时间 + 3600s”,用户可根据具体的业务场景对凭证截止时间进行调整。
	int deadline = QDateTime::currentDateTimeUtc().toTime_t() + 3600;
	obj["deadline"] = deadline;

	doc.setObject(obj);


	return Auth::genUploadToken(ak, sk, doc.toJson(QJsonDocument::Compact));
}
コード例 #14
0
std::string BuyoutManager::Serialize(const QMap<QString, Buyout> &buyouts) {
    QJsonDocument doc;
    QJsonObject root;
    for (QString hash : buyouts.uniqueKeys()) {
        Buyout buyout = buyouts.value(hash);
        if (buyout.type != BUYOUT_TYPE_NO_PRICE && (buyout.currency == CURRENCY_NONE || buyout.type == BUYOUT_TYPE_NONE))
            continue;
        if (buyout.type >= BuyoutTypeAsTag.size() || buyout.currency >= CurrencyAsTag.size()) {
            QLOG_WARN() << "Ignoring invalid buyout, type:" << buyout.type
                << "currency:" << buyout.currency;
            continue;
        }
        QJsonObject value;
        value.insert("value", buyout.value);
        value.insert("set_by", buyout.set_by);

        if (!buyout.last_update.isNull()){
            value.insert("last_update", (int) buyout.last_update.toTime_t());
        } else {
            // If last_update is null, set as the actual time
            value.insert("last_update", (int) QDateTime::currentDateTime().toTime_t());
        }

        value.insert("type", QString::fromStdString(BuyoutTypeAsTag[buyout.type]));
        value.insert("currency", QString::fromStdString(CurrencyAsTag[buyout.currency]));

        root.insert(hash, value);
    }
    doc.setObject(root);
    QByteArray result = doc.toJson();
    return result.toStdString();
}
コード例 #15
0
ファイル: collectmailsesb.cpp プロジェクト: privet56/qWebTest
void collectmailsesb::handleMailInfo()
{
    cleanupFiles("esb_*");

    QJsonDocument doc;

    QJsonObject data;
    QJsonObject datacontent;

    QMapIterator<QString, QJsonArray*> iMailsInfos(mailInfos);
    int _iMailsInfos = 0;
    while (iMailsInfos.hasNext())
    {
        //_iMailsInfos++;
        iMailsInfos.next();
        QString sSubject = iMailsInfos.key();
        QJsonArray* lMails = iMailsInfos.value();
        datacontent.insert(sSubject, QJsonValue(*lMails));
        _iMailsInfos += lMails->size();
    }

    data.insert("data", QJsonValue(datacontent));
    doc.setObject(data);

    QFile file(QString(getFN("esb_", "maildata")+".json"));
    file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
    file.write(doc.toJson(QJsonDocument::Compact));
    file.close();

    //TODO: delete QJsonArray*'s

    helpers::log("cmesb:handleMailInfo(esb): FINISH -> "+QString::number(_iMailsInfos), LOG_INF, qApp, 0);
}
コード例 #16
0
ファイル: database.cpp プロジェクト: jklmnn/ContaQts
QString Database::json_convert(Kind *kind){
    QJsonDocument *jdoc = new QJsonDocument;
    QJsonObject *root = new QJsonObject;
    root->insert(NAME, QJsonValue(kind->getName()));
    root->insert(SURNAME, QJsonValue(kind->getSurName()));
    root->insert(DATE, QJsonValue(kind->getDate().toString(DATESAVEFORMAT)));
    root->insert(STREET, QJsonValue(kind->getStreet()));
    root->insert(CITY, QJsonValue(kind->getCity()));
    root->insert(GROUP, QJsonValue(kind->getGroup()));
    root->insert(MAIL, QJsonValue(kind->getMail()));
    root->insert(NUMBER, QJsonValue(kind->getNumber()));
    QJsonObject *jtable = new QJsonObject;
    QJsonArray *keys = new QJsonArray;
    QJsonArray *tables = new QJsonArray;
    QJsonObject *values = new QJsonObject;
    std::map<QString, QString> *kt = kind->getTable();
    std::map<QString, QString>::iterator it;
    int i = 0;
    for(it = kt->begin(); it != kt->end(); it++){
        keys->insert(i, QJsonValue(it->first));
        values->insert(it->first, it->second);
        i++;
    }
    jtable->insert(KEY, QJsonValue(*keys));
    jtable->insert(VALUE, QJsonValue(*values));
    jtable->insert(NAME, QJsonValue(QString::fromStdString(TNAME)));
    tables->insert(0, QJsonValue(*jtable));
    root->insert(TABLE, QJsonValue(*tables));
    jdoc->setObject(*root);
    QString datefile = QString::fromUtf8(jdoc->toJson(QJsonDocument::Compact)) + QString::fromStdString(ENDL);
    return datefile;
}
コード例 #17
0
ファイル: maindialog.cpp プロジェクト: 821869798/CMDManager
void MainDialog::on_receiveBtn_clicked()
{
    int index = ui->listWidget->currentIndex().row();
    if(index==-1)
    {
        QMessageBox::about(NULL,"提示","没有选择内容");
    }
    else
    {
        QString info = ui->listWidget->item(index)->text();
        ui->listWidget->takeItem(index);
        if(itemTypeList.at(index)==0)
        {
            QJsonObject object;
            object.insert("info",info.left(10));
            object.insert("type",2);
            QJsonDocument document;
            document.setObject(object);
            QString msg(document.toJson());
            tcpSocket->write(msg.toLocal8Bit());
        }
        itemTypeList.remove(index);
        if(ui->listWidget->count()==0)
        {
            player->stop();
        }
    }
}
コード例 #18
0
void ApiClient::putResponse(QUrl url, QString headerName, QString headerValue) {
    // Request and get from manager
    qDebug() << "getResponse" << url.toString();
    QNetworkRequest req(url);
    req.setRawHeader("Content-Type", "application/json");

    QByteArray hName;
    hName.append(headerName);
    QByteArray hValue;
    hValue.append(headerValue);
    req.setRawHeader(hName, hValue);

    QJsonDocument wrap;
    QJsonObject object;

    QString b64SignalingKey(this->conf->getSignalingKey().toBase64());
    object["signalingKey"] = b64SignalingKey;
    object["supportsSms"] = false;
    object["registrationId"] = QString::number(this->conf->getRegistrationId());

    wrap.setObject(object);

    QNetworkReply *reply = this->mgr.put(req, wrap.toJson());

    // XXX: This is where the ssl must be ignored for it to work
    // but we haven't told the user yet what is ignored o_O
    // Potentially nasty
    reply->ignoreSslErrors();
    QObject::connect(reply, &QNetworkReply::sslErrors, this, &ApiClient::printSslErrors);

    // signal handler picks up from here
}
コード例 #19
0
void QPushbulletHandler::requestPush(Push &push, QString deviceID, QString email)
{
    /* [x] Note
     * [x] Link
     * [x] Address
     * [x] List
     * [] File
     */
    QJsonDocument jsonDocument;
    QJsonObject jsonObject;
    if (push.type == PUSH_TYPE::ADDRESS)
        jsonObject["type"] = "address";
    else if (push.type == PUSH_TYPE::FILE)
        jsonObject["type"] = "file";
    else if (push.type == PUSH_TYPE::LINK)
        jsonObject["type"] = "link";
    else if (push.type == PUSH_TYPE::LIST)
        jsonObject["type"] = "list";
    else if (push.type == PUSH_TYPE::NOTE)
        jsonObject["type"] = "note";

    if (!deviceID.isEmpty())
        jsonObject["device_iden"] = deviceID;
    else if (!email.isEmpty())
        jsonObject["email"] = email;
    if (push.type == PUSH_TYPE::NOTE) {
        jsonObject["title"] = push.title;
        jsonObject["body"] = push.body;
    }
    else if (push.type == PUSH_TYPE::LINK) {
        jsonObject["url"] = push.url;
        jsonObject["title"] = push.title;
        jsonObject["body"] = push.body;
    }
    else if (push.type == PUSH_TYPE::ADDRESS) {
        jsonObject["name"] = push.addressName;
        jsonObject["address"] = push.address;
    }
    else if (push.type == PUSH_TYPE::LIST) {
        jsonObject["type"] = "list";
        jsonObject["title"] = push.title;
        QJsonArray jsonArray;
        for (QString item : push.listItems) {
            jsonArray.append(QJsonValue(item));
        }
        jsonObject["items"] = jsonArray;
    }
    else if (push.type == PUSH_TYPE::FILE) {
        jsonObject["file_name"] = push.fileName;
        jsonObject["file_type"] = push.fileType;
        jsonObject["file_url"] = push.fileURL;
        jsonObject["body"] = push.body;
    }
    m_CurrentOperation = CURRENT_OPERATION::PUSH;

    jsonDocument.setObject(jsonObject);
    qDebug() << QString(jsonDocument.toJson());
    postRequest(m_URLPushes, jsonDocument.toJson());
}
コード例 #20
0
ファイル: TimerWindow.cpp プロジェクト: mnikn/ManageSystem
/**
 * @brief TimerWindow::getDataByDate 根据用户ID和日获取数据
 * @param data 存储有数据的QVector<double>对象
 * @param labels 存储有绘图文本的QVector<QString>对象
 * @param u_id 存储有用户id的int对象
 * @param beginDate 开始日期
 * @param endDate 结束日期
 * @return 成功:true,否则:false
 */
bool TimerWindow::getDataByDate(QVector<double> &data, QVector<QString> &labels,
                                int u_id, QDate &beginDate, QDate &endDate)
{
    if(u_id == -1){
        return false;
    }
    data.clear();
    labels.clear();

#ifdef USE_DB_HELPER
    QSqlQuery query;
    QString sql = "SELECT times,date FROM times WHERE user_id = ? AND date >= ? AND date <= ? ORDER BY date ASC";
    QStringList params;
    params.append(QString::number(u_id));
    params.append(beginDate.toString("yyyy-MM-dd"));
    params.append(endDate.toString("yyyy-MM-dd"));
//    qDebug()<<"u_id "<<QString::number(u_id);
//    qDebug()<<"beginDate "<<beginDate.toString("yyyy-MM-dd");
//    qDebug()<<"endDate "<<endDate.toString("yyyy-MM-dd");
//    int result = db.excuteSql(query, sql, params);
//    if(result != db.e_result::excuteSueecss){
//        emit signalSetStatus(tr("Get data error!code:")+QString::number(result),true);
//        return false;
//    }
    while(query.next()){
        data.append(query.value(0).toDouble() / 3600);//times
        labels.append(query.value(1).toString());//date
    }
#else
    //查询用户时间
    int code = -1;
    QString add = addHeader + "Times/getUserTimes";
    //生成post数据
    QJsonObject json;
    json.insert("user_id", QString::number(u_id));
    json.insert("start_date", beginDate.toString("yyyy-MM-dd"));
    json.insert("end_date", endDate.toString("yyyy-MM-dd"));
    QJsonDocument document;
    document.setObject(json);
    QByteArray postData = document.toJson(QJsonDocument::Compact);

    //向服务器发出post请求
    request.setUrl(QUrl(add));
    manager->post(request, postData);
    connect(manager, &QNetworkAccessManager::finished,
            [&](QNetworkReply *reply){
        //解析数据
        QJsonParseError jsonError;
        QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll(), &jsonError);
        if(jsonError.error == QJsonParseError::NoError){
            if(!(jsonDocument.isNull()||jsonDocument.isEmpty())&&jsonDocument.isObject()){
                code = jsonDocument.object().value("code").toInt();
                if(code == 0){//获取成功
                    QJsonArray timeArray = jsonDocument.object().value("times").toArray();
                    foreach (QJsonValue timeValue, timeArray) {
                        labels.append(timeValue.toObject().value("times_date").toString());
                        data.append((timeValue.toObject().value("times_count").toString()).toDouble()/3600);
                    }
                }
コード例 #21
0
ファイル: anki.cpp プロジェクト: a-rodin/qstardict
void Anki::execute(QStarDict::DictWidget *dictWidget) {
    auto translatedWord = dictWidget->translatedWord();
    auto cursor = dictWidget->translationView()->textCursor();
    QString translation;
    if (cursor.hasSelection()) {
        translation = cursor.selection().toHtml("UTF-8");
    } else {
        translation = dictWidget->translationView()->document()->toHtml("UTF-8");
    }

    QJsonObject requestObject;
    requestObject.insert("action", QString("addNote"));
    requestObject.insert("version", 6);
    QJsonObject paramsObject;
    QJsonObject noteObject;
    noteObject.insert("deckName", m_deckName);
    noteObject.insert("modelName", m_modelName);
    QJsonObject fieldsObject;
    fieldsObject.insert("Front", translatedWord);
    fieldsObject.insert("Back", translation);
    noteObject.insert("fields", fieldsObject);
    QJsonObject optionsObject;
    optionsObject.insert("allowDuplicate", m_allowDuplicates);
    noteObject.insert("options", optionsObject);
    QJsonArray tagsArray;
    noteObject.insert("tags", tagsArray);
    paramsObject.insert("note", noteObject);
    requestObject.insert("params", paramsObject);

    QJsonDocument requestDocument;
    requestDocument.setObject(requestObject);

    auto networkAccessManager = new QNetworkAccessManager(this);
    QNetworkRequest request(m_connectUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    connect(networkAccessManager, &QNetworkAccessManager::finished,
            [=](QNetworkReply *reply) {
            if (reply->error() == QNetworkReply::NoError) {
                auto cursor = dictWidget->translationView()->textCursor();
                if (cursor.hasSelection()) {
                    cursor.clearSelection();
                    dictWidget->translationView()->setTextCursor(cursor);
                }
            } else {
                QMessageBox::critical(dictWidget, tr("Anki error"),
                        tr("Unable to add the word to Anki: network error. <br>" \
                           "Check if Anki is running and " \
                           "<a href=\"https://ankiweb.net/shared/info/2055492159\">AnkiConnect</a> " \
                           "add-on is installed to Anki. You probably would like to also install " \
                           "<a href=\"https://ankiweb.net/shared/info/85158043\">Minimize to tray</a> "\
                           "add-on to Anki."));
            }
            networkAccessManager->deleteLater();
    });

    networkAccessManager->post(request, requestDocument.toJson());
}
コード例 #22
0
/**
 * @brief usernameMessage::getJsonString
 * @return  对应的单行Json字符串
 */
QByteArray usernameMessage::getJsonString()
{
    QJsonObject jsonObject;
    jsonObject.insert("head", head);
    jsonObject.insert("username", user);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(jsonObject);
    return jsonDocument.toJson(QJsonDocument::Compact);
}
コード例 #23
0
QByteArray NoronJsonBinarySerializer::serialize(QVariantMap map)
{
    QJsonValue val = toJson(map);
    QJsonDocument doc;

    doc.setObject(val.toObject());

    return doc.toJson();
}
コード例 #24
0
void MapleManager::showDBG(bool state)
{
    QJsonDocument doc;
    QJsonObject obj;
    obj[Packets::header_tag] = (int)Packets::Headers::DBG;
    obj["state"] = state;
    doc.setObject(obj);
    m_server->send(m_socket,doc);
}
コード例 #25
0
QByteArray ServerCommunicator::toJson(const double id, const QString header, const QString body) {
    QJsonObject obj;
    obj.insert("id", id);
    obj.insert("heading", header);
    obj.insert("body", body);
    QJsonDocument document;
    document.setObject(obj);
    return document.toJson();
}
コード例 #26
0
void RoomListDialog::requestRoomList()
{
    QJsonObject map;
    map.insert("request", QString("roomlist"));

    QJsonDocument doc;
    doc.setObject(map);
    socket->sendData(doc.toJson());
    ui->progressBar->setRange(0,0);
}
コード例 #27
0
void MapleManager::send(QString message, QString extension)
{
    QJsonDocument doc;
    QJsonObject obj;
    obj[Packets::header_tag] = (int)Packets::Headers::EXTENSION;
    obj[Packets::extension_tag] = extension;
    obj[Packets::content_tag] = message;
    doc.setObject(obj);
    m_server->send(m_socket,doc);
}
コード例 #28
0
ファイル: webuser.cpp プロジェクト: gvsurenderreddy/Centini
void WebUser::sendMessage(QVariantMap fields)
{
	if (socket_->state() != QAbstractSocket::ConnectedState)
		return;

	QJsonDocument message;
	message.setObject(QJsonObject::fromVariantMap(fields));

	socket_->sendTextMessage(message.toJson(/*QJsonDocument::Compact*/));
}
コード例 #29
0
void Connection::send(QString message, QString extension)
{    
    QJsonDocument doc;
    QJsonObject obj;
    obj[Packets::header_tag] = (int)Packets::Headers::EXTENSION;
    obj[Packets::extension_tag] = extension;
    obj[Packets::content_tag] = message;
    doc.setObject(obj);
    this->send(doc);
}
コード例 #30
0
ファイル: maindialog.cpp プロジェクト: 821869798/CMDManager
void MainDialog::tcpConnected()
{
    QJsonObject object;
    object.insert("name",name);
    object.insert("type",1);
    QJsonDocument document;
    document.setObject(object);
    QString message(document.toJson());
    tcpSocket->write(message.toLocal8Bit());
}