void RemDev::handleItem(char *data) { /*if (data.size() > MAX_TRANSACTION_SIZE) { // TODO return; }*/ QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(data, &error); // Check for registration before handling parsing errors because it will just // return if any errors occurred (we don't want to send anything to prevent // overload attacks if we're unregistered) if ( ! registered) { if ( ! doc.isObject()) return; handleRegistration(doc.object()); return; } if (error.error != QJsonParseError::NoError) { return; } if (doc.isArray()) { // TODO return; } if (doc.isObject()) { QJsonObject obj = doc.object(); handleObject(obj); return; } // TODO: Failed }
void Wagnis::validateRegistrationData(const QByteArray ®istrationData, const bool &saveData) { qDebug() << "Wagnis::validateRegistrationData"; QJsonDocument jsonDocument = QJsonDocument::fromJson(registrationData); if (jsonDocument.isObject()) { QJsonObject responseObject = jsonDocument.object(); QVariantMap registrationInformation = responseObject.toVariantMap(); QString registrationContent = registrationInformation.value("registration").toString(); QString registrationSignature = registrationInformation.value("signature").toString(); qDebug() << "[Wagnis] Payload: " << registrationContent; qDebug() << "[Wagnis] Signature: " << registrationSignature; QJsonDocument registrationContentJson = QJsonDocument::fromJson(registrationContent.toUtf8()); bool wagnisIdVerified = false; if (registrationContentJson.isObject()) { QVariantMap wagnisInformation = registrationContentJson.object().toVariantMap(); if ( wagnisInformation.value("id").toString() == this->wagnisId ) { qDebug() << "[Wagnis] ID verified!"; wagnisIdVerified = true; } } if (wagnisIdVerified && isSignatureValid(registrationContent, registrationSignature)) { qDebug() << "[Wagnis] Registration valid!"; this->validatedRegistration = registrationContentJson.object().toVariantMap(); QDateTime registrationTime = QDateTime::fromString(this->validatedRegistration.value("timestamp").toString(), "yyyy-MM-dd hh:mm:ss"); QDateTime currentTime = QDateTime::currentDateTime(); this->remainingSeconds = 1209600 - registrationTime.secsTo(currentTime); if (this->remainingSeconds < 0 ) { this->remainingSeconds = 0; } emit registrationValid(this->validatedRegistration); if (saveData) { QFile registrationFile(getRegistrationFileName()); if (registrationFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "[Wagnis] Writing registration file to " << registrationFile.fileName(); registrationFile.write(registrationData); registrationFile.close(); } } } else { qDebug() << "[Wagnis] Registration INVALID!"; emit registrationInvalid(); } } }
void QTwitchChat::onEmotIconsLoaded() { QNetworkReply *reply = qobject_cast< QNetworkReply * >( sender() ); QJsonParseError parseError; QJsonDocument jsonDoc; jsonDoc = QJsonDocument::fromJson( reply->readAll(), &parseError ); if( parseError.error == QJsonParseError::NoError ) { if( jsonDoc.isObject() ) { emotIcons_.clear(); QJsonArray jsonEmotIcons = jsonDoc.object()[ "emoticons" ].toArray(); foreach( const QJsonValue &value, jsonEmotIcons ) { QJsonObject jsonEmotIcon = value.toObject(); QChatSmile smile( jsonEmotIcon[ "regex" ].toString(), jsonEmotIcon[ "url" ].toString(), jsonEmotIcon[ "width" ].toInt(), jsonEmotIcon[ "height" ].toInt() ); //emotIcons_.append( smile ); emotIcons_.insert( smile.name(), smile ); } if( isShowSystemMessages() ) emit newMessage( new QChatMessage( TWITCH_SERVICE, TWITCH_USER, "Smiles ready...", "", this ) ); }
void Repository::requestedDataReceived(const QByteArray& data) noexcept { QJsonDocument doc = QJsonDocument::fromJson(data); if (doc.isNull() || doc.isEmpty() || (!doc.isObject())) { emit errorWhileFetchingLibraryList( tr("Received JSON object is not valid.")); return; } QJsonValue nextResultsLink = doc.object().value("next"); if (nextResultsLink.isString()) { QUrl url = QUrl(nextResultsLink.toString()); if (url.isValid()) { qDebug() << "Request more results from repository:" << url.toString(); requestLibraryList(url); } else { qWarning() << "Invalid URL in received JSON object:" << nextResultsLink.toString(); } } QJsonValue reposVal = doc.object().value("results"); if ((reposVal.isNull()) || (!reposVal.isArray())) { emit errorWhileFetchingLibraryList( tr("Received JSON object does not contain " "any results.")); return; } emit libraryListReceived(reposVal.toArray()); }
ExternalExtractor::ExternalExtractor(const QString& pluginPath) : ExtractorPlugin(new QObject()), d_ptr(new ExternalExtractorPrivate) { Q_D(ExternalExtractor); d->path = pluginPath; QDir pluginDir(pluginPath); QStringList pluginDirContents = pluginDir.entryList(); if (!pluginDirContents.contains(QStringLiteral("manifest.json"))) { qDebug() << "Path does not seem to contain a valid plugin"; return; } QFile manifest(pluginDir.filePath(QStringLiteral("manifest.json"))); manifest.open(QIODevice::ReadOnly); QJsonDocument manifestDoc = QJsonDocument::fromJson(manifest.readAll()); if (!manifestDoc.isObject()) { qDebug() << "Manifest does not seem to be a valid JSON Object"; return; } QJsonObject rootObject = manifestDoc.object(); QJsonArray mimetypesArray = rootObject.value(QStringLiteral("mimetypes")).toArray(); QStringList mimetypes; Q_FOREACH(QVariant mimetype, mimetypesArray) { mimetypes << mimetype.toString(); } d->writeMimetypes.append(mimetypes); d->mainPath = pluginDir.filePath(rootObject[QStringLiteral("main")].toString()); }
void AnnouncementApi::handleServerInfoResponse(QNetworkReply *reply) { QJsonParseError error; QByteArray body = reply->readAll(); QJsonDocument doc = QJsonDocument::fromJson(body, &error); if(error.error != QJsonParseError::NoError) throw ResponseError(QStringLiteral("Error parsing API response: %1").arg(error.errorString())); if(!doc.isObject()) throw ResponseError(QStringLiteral("Expected object!")); QJsonObject obj = doc.object(); QString apiname = obj.value("api_name").toString(); if(apiname != "drawpile-session-list") throw ResponseError(QStringLiteral("This is not a Drawpile listing server!")); ListServerInfo info { obj.value("version").toString(), obj.value("name").toString().trimmed(), obj.value("description").toString().trimmed(), obj.value("favicon").toString() }; if(info.version.isEmpty()) throw ResponseError(QStringLiteral("API version not specified!")); if(!info.version.startsWith("1.")) throw ResponseError(QStringLiteral("Unsupported API version!")); if(info.name.isEmpty()) throw ResponseError(QStringLiteral("Server name missing!")); emit serverInfo(info); }
void MainWindow::itemPosted() { QNetworkReply *reply = senderAsReply(); if (reply == nullptr) { return; } int index = mQueries.indexOf(reply); mQueries.removeAt(index); QListWidgetItem *item = mItemsToUpdate.takeAt(index); if (reply->error() != QNetworkReply::NoError) { return; } QJsonDocument json = jsonFromReply(reply); if (!json.isObject()) { logMessage(tr("Error: not object")); return; } QJsonObject task = json.object(); item->setData(Qt::UserRole, task["id"].toVariant()); }
void MessageTest::parse() { // Fetch the current filename and load it into a ReferenceString QFETCH(QString, filename); filename.prepend("message-ref/"); ReferenceString refStr(filename); // Parse the doc and create a message QJsonDocument doc = QJsonDocument::fromJson(refStr.toString().toLatin1()); QVERIFY(doc.isObject()); QJsonObject refObj = doc.object(); QJsonValue origId; // Fixup the ids so that the MessageIdManager can resolve them. if (refObj.contains("id")) { Message request(Message::Request, &m_conn); request.setMethod("testMethod"); QVERIFY(request.send()); m_conn.popMessage(); origId = refObj.value("id"); refObj["id"] = request.id(); } // Parse the message Message message(refObj); QVERIFY(message.parse()); // Reset the id if needed if (!origId.isNull()) message.setId(origId); // Compare strings QCOMPARE(refStr.toString(), QString(message.toJson())); }
bool CategoryParser::parse(const QString &fileName) { m_exploreObject = QJsonObject(); m_tree.clear(); m_errorString.clear(); QFile mappingFile(fileName); if (mappingFile.open(QIODevice::ReadOnly)) { QJsonDocument document = QJsonDocument::fromJson(mappingFile.readAll()); if (document.isObject()) { QJsonObject docObject = document.object(); if (docObject.contains(QLatin1String("offline_explore"))) { m_exploreObject = docObject.value(QLatin1String("offline_explore")) .toObject(); if (m_exploreObject.contains(QLatin1String("ROOT"))) { processCategory(0, QString()); return true; } } else { m_errorString = fileName + QLatin1String("does not contain the " "offline_explore property"); return false; } } else { m_errorString = fileName + QLatin1String("is not an json object"); return false; } } m_errorString = QString::fromLatin1("Unable to open ") + fileName; return false; }
QJsonObject loadJsonObjectFromResource(const QString &resource, QString *error) { QFile file(resource); if (file.open(QFile::ReadOnly)) { QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &parseError); if (parseError.error == QJsonParseError::NoError) { if (doc.isObject()) return doc.object(); else { if (error) { *error = QStringLiteral("JSON doesn't contain a main object."); } } } else { if (error) { *error = parseError.errorString(); } } } else { if (error) { *error = QStringLiteral("Unable to open file."); } } return QJsonObject(); }
void QVidiChat::onStatisticLoaded() { QNetworkReply * reply = qobject_cast< QNetworkReply * >( sender() ); QJsonParseError parseError; QJsonDocument jsonDoc = QJsonDocument::fromJson( reply->readAll(), &parseError ); if( QJsonParseError::NoError == parseError.error && jsonDoc.isObject() ) { QJsonObject jsonObj = jsonDoc.object(); QJsonObject jsonUser = jsonObj[ "user" ].toObject(); QJsonObject jsonChannel = jsonUser[ "Channel" ].toObject(); QString statistic = QString::number( jsonChannel[ "viewers" ].toInt() ); if( !jsonChannel[ "online" ].toBool() ) statistic = "0"; emit newStatistic( new QChatStatistic( SERVICE_NAME, statistic, this ) ); } reply->deleteLater(); }
QString Api::getPatcherSecret(const QString &appSecret, CancellationToken cancellationToken) const { qInfo() << "Getting the patcher secret for app " << appSecret; auto path = QString("1/apps/%1") .arg(appSecret); QJsonDocument document = get(path, cancellationToken); if (!document.isObject()) { throw InvalidFormatException("Expected document root to be object"); } if (!document.object().contains("patcher_secret")) { throw InvalidFormatException("Document did not contain the 'patcher_secret' field"); } if (!document.object()["patcher_secret"].isString()) { throw InvalidFormatException("patcher_secret was not a string"); } return document.object()["patcher_secret"].toString(); }
int Api::getLatestAppVersion(const QString &appSecret, CancellationToken cancellationToken) const { qInfo() << "Getting the latest app version for app " << appSecret; auto path = QString("1/apps/%1/versions/latest/id") .arg(appSecret); QJsonDocument document = get(path, cancellationToken); if (!document.isObject()) { throw InvalidFormatException("Expected document root to be object"); } if (!document.object().contains("id")) { throw InvalidFormatException("Document did not contain the 'id' field"); } if (!document.object()["id"].isDouble()) { } int id = document.object()["id"].toInt(-1); if (id == -1) { throw InvalidFormatException("Value of 'id' field was not an integer"); } return id; }
/**jsdoc * A material or set of materials such as may be used by a {@link Entities.EntityType|Material} entity. * @typedef {object} MaterialResource * @property {number} materialVersion=1 - The version of the material. <em>Currently not used.</em> * @property {Material|Material[]} materials - The details of the material or materials. */ NetworkMaterialResource::ParsedMaterials NetworkMaterialResource::parseJSONMaterials(const QJsonDocument& materialJSON, const QUrl& baseUrl) { ParsedMaterials toReturn; if (!materialJSON.isNull() && materialJSON.isObject()) { QJsonObject materialJSONObject = materialJSON.object(); for (auto& key : materialJSONObject.keys()) { if (key == "materialVersion") { auto value = materialJSONObject.value(key); if (value.isDouble()) { toReturn.version = (uint)value.toInt(); } } else if (key == "materials") { auto materialsValue = materialJSONObject.value(key); if (materialsValue.isArray()) { QJsonArray materials = materialsValue.toArray(); for (auto material : materials) { if (!material.isNull() && material.isObject()) { auto parsedMaterial = parseJSONMaterial(material.toObject(), baseUrl); toReturn.networkMaterials[parsedMaterial.first] = parsedMaterial.second; toReturn.names.push_back(parsedMaterial.first); } } } else if (materialsValue.isObject()) { auto parsedMaterial = parseJSONMaterial(materialsValue.toObject(), baseUrl); toReturn.networkMaterials[parsedMaterial.first] = parsedMaterial.second; toReturn.names.push_back(parsedMaterial.first); } } } } return toReturn; }
bool Parser::parseCoachesSearchResults(QByteArray &data, Train &train,QString coachType) { CreateJsonFileForTest(data,"test_SearchCoachesReply.json"); QJsonDocument responce; responce = QJsonDocument::fromJson(data); if (responce.isObject()) { QJsonObject jsonobject = responce.object(); //QJsonObject jsonValue = jsonobject["value"].toObject(); //QJsonArray jsonCoaches = jsonValue["coaches"].toArray(); QJsonArray jsonCoaches = jsonobject["coaches"].toArray(); QJsonObject jsonCoach; for(auto it = jsonCoaches.begin();it != jsonCoaches.end();++it) { jsonCoach = it->toObject(); int number = jsonCoach["num"].toInt(); Coach coach(number); coach.coachTypeID = QString::number(jsonCoach["coach_type_id"].toInt()); coach.placesNumber = jsonCoach["places_cnt"].toInt(); coach.coachClass = coachType; //qDebug()<<coachType; train.coaches.insert(number,coach); } return true; } return false; }
std::shared_ptr<OneSixVersion> OneSixVersion::fromFile(QString filepath) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { return std::shared_ptr<OneSixVersion>(); } auto data = file.readAll(); QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error != QJsonParseError::NoError) { return std::shared_ptr<OneSixVersion>(); } if (!jsonDoc.isObject()) { return std::shared_ptr<OneSixVersion>(); } QJsonObject root = jsonDoc.object(); auto version = fromJson(root); if (version) version->original_file = filepath; return version; }
std::vector<CGorjunFileInfo> CRestWorker::get_gorjun_file_info(const QString &file_name) { static const QString str_fi("file/info"); int http_code, err_code, network_error; QUrl url_gorjun_fi(CSettingsManager::Instance().gorjun_url().arg(str_fi)); QUrlQuery query_gorjun_fi; query_gorjun_fi.addQueryItem("name", file_name); url_gorjun_fi.setQuery(query_gorjun_fi); QNetworkRequest request(url_gorjun_fi); request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json"); QByteArray arr = send_get_request(request, http_code, err_code, network_error); QJsonDocument doc = QJsonDocument::fromJson(arr); std::vector<CGorjunFileInfo> lst_res; if (doc.isNull()) { err_code = RE_NOT_JSON_DOC; return lst_res; } if (doc.isArray()) { QJsonArray json_arr = doc.array(); for (auto i = json_arr.begin(); i != json_arr.end(); ++i) { if (i->isNull() || !i->isObject()) continue; lst_res.push_back(CGorjunFileInfo(i->toObject())); } } else if (doc.isObject()) { lst_res.push_back(CGorjunFileInfo(doc.object())); } return lst_res; }
DomainServerSettingsManager::DomainServerSettingsManager() : _descriptionArray(), _configMap() { // load the description object from the settings description QFile descriptionFile(QCoreApplication::applicationDirPath() + SETTINGS_DESCRIPTION_RELATIVE_PATH); descriptionFile.open(QIODevice::ReadOnly); QJsonDocument descriptionDocument = QJsonDocument::fromJson(descriptionFile.readAll()); if (descriptionDocument.isObject()) { QJsonObject descriptionObject = descriptionDocument.object(); const QString DESCRIPTION_VERSION_KEY = "version"; if (descriptionObject.contains(DESCRIPTION_VERSION_KEY)) { // read the version from the settings description _descriptionVersion = descriptionObject[DESCRIPTION_VERSION_KEY].toDouble(); if (descriptionObject.contains(DESCRIPTION_SETTINGS_KEY)) { _descriptionArray = descriptionDocument.object()[DESCRIPTION_SETTINGS_KEY].toArray(); return; } } } static const QString MISSING_SETTINGS_DESC_MSG = QString("Did not find settings decription in JSON at %1 - Unable to continue. domain-server will quit.") .arg(SETTINGS_DESCRIPTION_RELATIVE_PATH); static const int MISSING_SETTINGS_DESC_ERROR_CODE = 6; QMetaObject::invokeMethod(QCoreApplication::instance(), "queuedQuit", Qt::QueuedConnection, Q_ARG(QString, MISSING_SETTINGS_DESC_MSG), Q_ARG(int, MISSING_SETTINGS_DESC_ERROR_CODE)); }
inline bool loadDocument(const std::string &path, QJsonValue &root) { // Load schema JSON from file QFile file(QString::fromStdString(path)); if (!file.open(QFile::ReadOnly)) { std::cerr << "Failed to load json from file '" << path << "'." << std::endl; return false; } QByteArray data = file.readAll(); // Parse schema QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(data); if (doc.isNull()) { std::cerr << "qt failed to parse the document:" << std::endl << parseError.errorString().toStdString() << std::endl; return false; } else if (doc.isObject()) { root = QJsonValue(doc.object()); } else if (doc.isArray()) { root = QJsonValue(doc.array()); } else if (doc.isEmpty()) { root = QJsonValue(); } return true; }
void JsonSnippetTranslatorTest::translatesSnippetCollectionToJsonDocument() { Snippet snippet; snippet.trigger = "trigger"; snippet.description = "description"; snippet.snippet = "snippet"; snippet.cursorPosition = 1; snippet.builtIn = true; SnippetCollection collection; collection.insert(snippet); QJsonObject expected; expected.insert("trigger", snippet.trigger); expected.insert("description", snippet.description); expected.insert("snippet", snippet.snippet); expected.insert("cursor", snippet.cursorPosition); expected.insert("builtIn", snippet.builtIn); QJsonDocument actual = translator->createDocument(&collection); QVERIFY(actual.isObject()); QVERIFY(actual.object().contains("snippets")); QVERIFY(actual.object().value("snippets").isArray()); QJsonObject actualObject = actual.object().value("snippets").toArray().first().toObject(); QCOMPARE(actualObject["trigger"], expected["trigger"]); QCOMPARE(actualObject["description"], expected["description"]); QCOMPARE(actualObject["snippet"], expected["snippet"]); QCOMPARE(actualObject["cursorPosition"], expected["cursorPosition"]); QCOMPARE(actualObject["builtIn"], expected["builtIn"]); }
void PoolBrowser::parseCurrencyUSD(QNetworkReply *reply) { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString data = reply->readAll(); QString bitcoin; QJsonParseError jsonParseError; QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8(), &jsonParseError); if (jsonResponse.isObject()) { QJsonObject mainObject = jsonResponse.object(); if (mainObject.contains("bpi")) { QJsonObject bpiObject = mainObject["bpi"].toObject(); QJsonObject USDObject = bpiObject["USD"].toObject(); bitcoin = USDObject["rate"].toString(); bitcoinToUSD = bitcoin.toDouble(); } } if(bitcoin > bitcoinp) { ui->bitcoin->setText("<b><font color=\"green\">" + bitcoin + " $</font></b>"); } else if (bitcoin < bitcoinp) { ui->bitcoin->setText("<b><font color=\"red\">" + bitcoin + " $</font></b>"); } else { ui->bitcoin->setText(bitcoin + " $"); } bitcoinp = bitcoin; }
void ServerConfigurator::processSocketMessage(QString *message) { QJsonDocument d = QJsonDocument::fromJson(message->toUtf8()); if (d.isObject()) { QJsonObject jsonObj = d.object(); QString event = jsonObj["event"].toString(); if (event == "insert_text") { QString text = jsonObj["data"].toString(); processInsertText(text); } else if (event == "send_key_return") { processKeyReturn(); } else if (event == "send_key_del") { processKeyDel(); } else if (event == "send_key_arrow") { QString direction = jsonObj["data"].toString(); processKeyArrow(direction); } else { qDebug() << "unknown websocket event received: " << event; } } }
void Settings::readDriverFile() { QFile *file = new QFile(driver_path_); if (!file->open(QIODevice::ReadOnly)) throw DriverFileReadException("Unable to open the driver file"); QByteArray data = file->readAll(); QJsonDocument json = QJsonDocument::fromJson(data); if (json.isNull()) throw DriverFileJsonParsingException("Unable to parse the input file to JSON."); if (!json.isObject()) throw DriverFileFormatException("Driver file format incorrect. Must be a JSON object."); json_driver_ = new QJsonObject(json.object()); readGlobalSection(); readSimulatorSection(); readModelSection(); readOptimizerSection(); if (!constraintNamesCorrespondToVariables()) throw DriverFileInconsistentException("Constraint names must correspond to variable names."); file->close(); }
void WebQQNet::httpExtInfoFinished(QNetworkReply* reply){ qDebug()<<"httpPollFinished"<<endl; QByteArray replyData=reply->readAll(); // replyData.replace("\xe2\x80\xae","");//字符串中包含这几个字符,会莫名其妙的反转显示,非常奇特! // replyData.replace("\xe2\x80\xa8","");//导致回车换行 //由于有些群成员名片是非法utf-8字符,导致json数据解析错误只好自己使用replystr.toUtf8()再转一次 reply->deleteLater(); QString replystr=QString::fromUtf8(replyData); QQgroup*pGroup=WebQQ::qqGroups.value(currGroupTXUIN,nullptr); if(pGroup==nullptr){ qDebug()<<"httpExtInfoFinished 查无此群!"<<endl; return; } QJsonDocument jsonDoc; QJsonObject jsonObj; QJsonArray jsonArray; int retcode=0; QJsonParseError jsonError; jsonDoc=QJsonDocument::fromJson(replystr.toUtf8(),&jsonError); // qDebug()<<"httpPollFinished"<<jsonDoc<<endl; if(jsonDoc.isObject()){ jsonObj=jsonDoc.object(); retcode=jsonObj.value("retcode").toDouble(); if(retcode==0){ jsonObj=jsonObj.value("result").toObject(); jsonArray=jsonObj.value("minfo").toArray(); foreach(QJsonValue jv,jsonArray){ QJsonObject jo=jv.toObject(); QQfriend *f=new QQfriend(); f->txuin=QString::number(jo.value("uin").toDouble(),'f',0); f->nick=jo.value("nick").toString(); pGroup->members.insert(f->txuin,f); }
void RestInputStruct::ParseBodyIntoJson(){ //qDebug() << "Parse Body Into JSON"; while(Body.endsWith("\n")){ Body.chop(1); } if(Body.startsWith("{") && Body.endsWith("}") ){ QJsonDocument doc = QJsonDocument::fromJson(Body.toUtf8()); if(!doc.isNull() && doc.isObject() ){ //Valid JSON found if(doc.object().contains("namespace") ){ namesp = doc.object().value("namespace").toString(); } if(doc.object().contains("name") ){ name = doc.object().value("name").toString(); } if(doc.object().contains("id") ){ id = doc.object().value("id").toString(); } if(doc.object().contains("args") ){ args = doc.object().value("args"); } else{ //no args structure - treat the entire body as the arguments struct args = doc.object(); } } }else{ qDebug() << " -Could not find JSON!!"; qDebug() << " - Body:" << Body; } //Now do any REST -> JSON conversions if necessary if(!URI.isEmpty()){ //TO-DO name = URI.section("/",-1); //last entry namesp = URI.section("/",1,1); //URI excluding name } }
QList<QString> SingleWeatherParamWidget::getDataFromJson(QString jsonStr){ QList<QString> valueList; QJsonParseError jsonErr; QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8(), &jsonErr); if(jsonErr.error == QJsonParseError::NoError){ if(!jsonDoc.isEmpty()){ if(jsonDoc.isObject()){ QJsonObject jobj = jsonDoc.object(); QJsonObject::iterator it = jobj.begin(); while(it != jobj.end()){ if(QJsonValue::Array == it.value().type()){ QJsonArray array = it.value().toArray(); int subArrayCount = array.count(); for(int i = 0;i < subArrayCount;i++){ QJsonArray subArray = array.at(i).toArray(); valueList.append(subArray.at(0).toString()); valueList.append(subArray.at(1).toString()); } } it++; } } } } return valueList; }
void QPlaceContentReplyImpl::replyFinished() { if (m_reply->isOpen()) { QJsonDocument document = QJsonDocument::fromJson(m_reply->readAll()); if (!document.isObject()) { setError(ParseError, QCoreApplication::translate(NOKIA_PLUGIN_CONTEXT_NAME, PARSE_ERROR)); return; } QJsonObject object = document.object(); QPlaceContent::Collection collection; int totalCount; QPlaceContentRequest previous; QPlaceContentRequest next; parseCollection(request().contentType(), object, &collection, &totalCount, &previous, &next, m_engine); setTotalCount(totalCount); setContent(collection); setPreviousPageRequest(previous); setNextPageRequest(next); } m_reply->deleteLater(); m_reply = 0; setFinished(true); emit finished(); }
void LoginManager::onReplyFinished(QNetworkReply* reply, RequestType requestType) { if (!reply) return; const int code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); QByteArray ba(reply->readAll()); QJsonObject obj; if (!ba.isEmpty()) { QJsonDocument jsonResponse = QJsonDocument::fromJson(ba); if (jsonResponse.isObject()) obj = jsonResponse.object(); } switch (requestType) { case RequestType::LOGIN: onLoginReply(reply, code, obj); break; case RequestType::GET_USER_INFO: onGetUserReply(reply, code, obj); break; case RequestType::GET_SCORE_INFO: onGetScoreInfoReply(reply, code, obj); break; case RequestType::UPLOAD_SCORE: onUploadReply(reply, code, obj); break; case RequestType::GET_MEDIA_URL: onGetMediaUrlReply(reply, code, obj); break; } reply->deleteLater(); }
/** * @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); } }
bool genius::parseArtist() { QJsonParseError jsonParseError; QJsonDocument jsonResponse = QJsonDocument::fromJson(static_cast<QString>(this->array).toUtf8(), &jsonParseError); if (jsonParseError.error != QJsonParseError::NoError) return false; if (!jsonResponse.isObject()) return false; qDebug()<<"parsing artist info1"; QJsonObject mainJsonObject(jsonResponse.object()); auto data = mainJsonObject.toVariantMap(); auto itemMap = data.value("response").toMap().value("artist").toMap(); qDebug()<<"parsing artist info2"; if(itemMap.isEmpty()) return false; VALUE contexts; qDebug()<<"parsing artist info3"; if(this->info == INFO::TAGS || this->info == INFO::ALL) { auto alias = itemMap.value("alternate_names").toStringList(); contexts.insert(CONTEXT::ARTIST_ALIAS, alias); auto followers = itemMap.value("followers_count").toString(); contexts.insert(CONTEXT::ARTIST_STAT, followers ); emit this->infoReady(this->track,this->packResponse(ONTOLOGY::ARTIST, INFO::TAGS, contexts)); if(this->info == INFO::TAGS ) return true; } if(this->info == INFO::WIKI || this->info == INFO::WIKI) { QString wikiData; for(auto wiki : itemMap.value("description").toMap().value("dom").toMap().value("children").toList()) { for(auto child : wiki.toMap().value("children").toStringList() ) wikiData = wikiData + child; } contexts.insert( CONTEXT::WIKI, wikiData); emit this->infoReady(this->track,this->packResponse(ONTOLOGY::ARTIST, INFO::WIKI, contexts)); if(!wikiData.isEmpty() && this->info == INFO::WIKI) return true; } if(this->info == INFO::ARTWORK || this->info == INFO::ALL) { auto artwork = itemMap.value("image_url").toString(); emit this->infoReady(this->track,this->packResponse(ONTOLOGY::ARTIST, INFO::ARTWORK,CONTEXT::IMAGE,this->startConnection(artwork))); if(!artwork.isEmpty() && this->info == INFO::ARTWORK ) return true; } return false; }