本文整理汇总了C++中QJsonDocument函数的典型用法代码示例。如果您正苦于以下问题:C++ QJsonDocument函数的具体用法?C++ QJsonDocument怎么用?C++ QJsonDocument使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了QJsonDocument函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: QJsonDocument
void QRestClient::oAuthLogin(
QVariant id,
QVariant secret,
jsonPayloadFn successCb,
jsonPayloadFn errCb)
{
QJsonObject clientCredentials
{
{"client_id", QJsonValue::fromVariant(id)},
{"client_secret", QJsonValue::fromVariant(secret)},
{"grant_type", QJsonValue::fromVariant("client_credentials")}
};
this->asyncJsonCall("post", "oauth/access_token",
QJsonDocument(clientCredentials),
//Success callback
[this, successCb, errCb](QJsonDocument payload){
if(!payload.isObject() || !payload.object().contains("access_token")) {
//Custom oAuth Error
if(errCb)
errCb(buildJsonError("OAuth2: Error while getting bearer token", payload.toJson()));
return;
}
this->m_oAuthToken = payload.object()["access_token"].toVariant().toByteArray();
this->setAuthMethod(OAuth2);
if(successCb)
successCb(QJsonDocument());
//For other errors
},
errCb
);
}
示例2: toBinaryData
/*!
Creates a QJsonDocument from \a data.
\a validation decides whether the data is checked for validity before being used.
By default the data is validated. If the \a data is not valid, the method returns
a null document.
\sa toBinaryData(), fromRawData(), isNull(), DataValidation
*/
QJsonDocument QJsonDocument::fromBinaryData(const QByteArray &data, DataValidation validation)
{
if (data.size() < (int)(sizeof(QJsonPrivate::Header) + sizeof(QJsonPrivate::Base)))
return QJsonDocument();
QJsonPrivate::Header h;
memcpy(&h, data.constData(), sizeof(QJsonPrivate::Header));
QJsonPrivate::Base root;
memcpy(&root, data.constData() + sizeof(QJsonPrivate::Header), sizeof(QJsonPrivate::Base));
// do basic checks here, so we don't try to allocate more memory than we can.
if (h.tag != QJsonDocument::BinaryFormatTag || h.version != 1u ||
sizeof(QJsonPrivate::Header) + root.size > (uint)data.size())
return QJsonDocument();
const uint size = sizeof(QJsonPrivate::Header) + root.size;
char *raw = (char *)malloc(size);
if (!raw)
return QJsonDocument();
memcpy(raw, data.constData(), size);
QJsonPrivate::Data *d = new QJsonPrivate::Data(raw, size);
if (validation != BypassValidation && !d->valid()) {
delete d;
return QJsonDocument();
}
return QJsonDocument(d);
}
示例3: qDebug
void Application::incomingGuiMessage(const QJsonDocument& message) {
try {
// The message contains a JSON object of the GenericMessage
common::GenericMessage msg = common::GenericMessage(message);
qDebug() << "Received message of type " << msg.type;
if (msg.type == common::GuiStartCommand::Type) {
// We have received a message from the GUI to start a new application
handleIncomingGuiStartCommand(
common::GuiStartCommand(QJsonDocument(msg.payload))
);
} else if (msg.type == common::GuiProcessCommand::Type) {
// We have received a message from the GUI to start a new application
handleIncomingGuiProcessCommand(
common::GuiProcessCommand(QJsonDocument(msg.payload))
);
}
else if (msg.type == "GuiReloadConfigCommand") {
// We have received a message from the GUI to reload the configs
handleIncomingGuiReloadConfigCommand();
}
} catch (const std::runtime_error& e) {
Log(QString("Error with incoming gui message: ") + e.what());
Log(message.toJson());
}
}
示例4: logDebug
void MainWindow::enginioFinished(EnginioReply *msg)
{
if(msg->errorType() != EnginioReply::NoError) {
return;
}
logDebug(QJsonDocument(msg->data()).toJson());
if(msg == m_exportReply) {
QJsonArray jsonArray(m_exportReply->data().value("results").toArray());
QByteArray jsonText = QJsonDocument(jsonArray).toJson();
QFile exportFile(m_exportFile->text());
bool ok = exportFile.open(QIODevice::WriteOnly);
if(ok) {
exportFile.write(jsonText);
log(tr("%1 object(s) exported to %2").arg(jsonArray.size()).arg(exportFile.fileName()));
}
else {
logError(tr("Error %1 opening file %2").arg(exportFile.error()).arg(exportFile.fileName()));
}
}
if(msg == m_queryForRemovalReply) {
QJsonArray jsonArray(m_queryForRemovalReply->data().value("results").toArray());
foreach(const QJsonValue &v, jsonArray) {
QJsonObject removeObject(v.toObject());
setObjectType(&removeObject);
m_client->remove(removeObject);
}
示例5: if
void LocationService::getImpl(const QByteArray& operation, const APIParameters ¶meters, APIServiceResponse &response)
{
if(operation=="list")
{
//for now, this does not return location objects (which would require a much larger data transfer), but only the location strings
//same as in the LocationDialog list
//TODO not fully thread safe
QJsonArray list = QJsonArray::fromStringList(QStringList(locMgr->getAllMap().keys()));
response.writeJSON(QJsonDocument(list));
}
else if(operation == "countrylist")
{
const StelTranslator& trans = *StelTranslator::globalTranslator;
QStringList allCountries = StelApp::getInstance().getLocaleMgr().getAllCountryNames();
QJsonArray list;
foreach(QString str, allCountries)
{
QJsonObject obj;
obj.insert("name",str);
obj.insert("name_i18n",trans.qtranslate(str));
list.append(obj);
}
response.writeJSON(QJsonDocument(list));
}
示例6: cw
QJsonDocument jsonparser::jsonOpenFile(QString filename){
QFile jDocFile;
QFileInfo cw(filename);
if(startDir.isEmpty()){
startDir = cw.absolutePath();
jDocFile.setFileName(startDir+"/"+cw.fileName());
}else
jDocFile.setFileName(startDir+"/"+cw.fileName());
if (!jDocFile.exists()) {
sendProgressTextUpdate(tr("Failed due to the file %1 not existing").arg(jDocFile.fileName()));
return QJsonDocument();
}
if (!jDocFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
sendProgressTextUpdate(tr("Failed to open the requested file"));
return QJsonDocument();
}
QJsonParseError initError;
QJsonDocument jDoc = QJsonDocument::fromJson(jDocFile.readAll(),&initError);
if (initError.error != 0){
reportError(2,tr("ERROR: jDoc: %s\n").arg(initError.errorString()));
sendProgressTextUpdate(tr("An error occured. Please take a look at the error message to see what went wrong."));
return QJsonDocument();
}
if (jDoc.isNull() || jDoc.isEmpty()) {
sendProgressTextUpdate(tr("Failed to import file"));
return QJsonDocument();
}
return jDoc;
}
示例7: if
void ScriptService::getImpl(const QByteArray& operation, const APIParameters ¶meters, APIServiceResponse &response)
{
if(operation=="list")
{
//list all scripts, this should be thread safe
QStringList allScripts = scriptMgr->getScriptList();
response.writeJSON(QJsonDocument(QJsonArray::fromStringList(allScripts)));
}
else if (operation == "info")
{
if(parameters.contains("id"))
{
//retrieve detail about a single script
QString scriptId = QString::fromUtf8(parameters.value("id"));
if(parameters.contains("html"))
{
QString html = scriptMgr->getHtmlDescription(scriptId, false);
response.setHeader("Content-Type","text/html; charset=UTF-8");
response.setData(wrapHtml(html, scriptId).toUtf8());
return;
}
QJsonObject obj;
//if the script name is wrong, this will return empty strings
obj.insert("id",scriptId);
QString d = scriptMgr->getName(scriptId).trimmed();
obj.insert("name",d);
obj.insert("name_localized", StelTranslator::globalTranslator->qtranslate(d));
d = scriptMgr->getDescription(scriptId).trimmed();
obj.insert("description",d);
obj.insert("description_localized", StelTranslator::globalTranslator->qtranslate(d));
obj.insert("author",scriptMgr->getAuthor(scriptId).trimmed());
obj.insert("license",scriptMgr->getLicense(scriptId).trimmed());
//shortcut often causes a large delay because the whole file gets searched, and it is usually missing, so we ignore it
//obj.insert("shortcut",scriptMgr->getShortcut(scriptId));
response.writeJSON(QJsonDocument(obj));
}
else
{
response.writeRequestError("need parameter: id");
}
}
else if(operation == "status")
{
//generic script status
QJsonObject obj;
obj.insert("scriptIsRunning",scriptMgr->scriptIsRunning());
obj.insert("runningScriptId",scriptMgr->runningScriptId());
response.writeJSON(QJsonDocument(obj));
}
else
{
//TODO some sort of service description?
response.writeRequestError("unsupported operation. GET: list,info,status POST: run,stop");
}
}
示例8: sendJWT
QNetworkReply* MNetworkManager::sendJWT(const QString url, QJsonObject ¶ms, QString method ) {
QJsonObject header;
header["typ"] = "JWT";
header["alg"] = "sha256";
QByteArray encode;
encode.append(QJsonDocument(header).toJson().toBase64(QByteArray::Base64Encoding));
encode.append(".");
encode.append(QJsonDocument(params).toJson().toBase64(QByteArray::Base64Encoding));
QByteArray signature = QMessageAuthenticationCode::hash(encode, QByteArray(SECRET), QCryptographicHash::Sha256).toHex();
QByteArray jwt;
jwt.append(encode);
jwt.append(".");
jwt.append(signature);
QString apiUrl = APIHOST;
apiUrl.append(url);
QNetworkRequest request;
request.setUrl(QUrl(apiUrl));
request.setRawHeader("JWT", jwt);
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QNetworkReply* reply;
if (method == "post") {
reply = this->post(request,multiPart);
} else {
reply = this->get(request);
}
multiPart->setParent(reply);
return reply;
}
示例9: exp
void LocationSearchService::getImpl(const QByteArray& operation, const APIParameters ¶meters, APIServiceResponse &response)
{
if(operation=="search")
{
//parameter must be named "term" to be compatible with jQuery UI autocomplete without further JS code
QString term = QString::fromUtf8(parameters.value("term"));
if(term.isEmpty())
{
response.writeRequestError("needs non-empty 'term' parameter");
return;
}
//the filtering in the app is provided by QSortFilterProxyModel in the view
//we dont have that luxury, but we make sure the filtering happens in the separate HTTP thread
locMgrMutex.lock();
LocationMap allItems = locMgr.getAllMap();
locMgrMutex.unlock();
QJsonArray results;
const QList<QString>& list = allItems.keys();
//use a regexp in wildcard mode, the app does the same
QRegExp exp(term,Qt::CaseInsensitive, QRegExp::Wildcard);
for(QList<QString>::const_iterator it = list.begin();it!=list.end();++it)
{
if(it->contains(exp))
results.append(*it);
}
response.writeJSON(QJsonDocument(results));
}
else if(operation=="nearby")
{
QString sPlanet = QString::fromUtf8(parameters.value("planet"));
QString sLatitude = QString::fromUtf8(parameters.value("latitude"));
QString sLongitude = QString::fromUtf8(parameters.value("longitude"));
QString sRadius = QString::fromUtf8(parameters.value("radius"));
float latitude = sLatitude.toFloat();
float longitude = sLongitude.toFloat();
float radius = sRadius.toFloat();
locMgrMutex.lock();
LocationMap results = locMgr.pickLocationsNearby(sPlanet,longitude,latitude,radius);
locMgrMutex.unlock();
response.writeJSON(QJsonDocument(QJsonArray::fromStringList(results.keys())));
}
else
{
//TODO some sort of service description?
response.writeRequestError("unsupported operation. GET: search,nearby");
}
}
示例10: hearthbeatReceived
void NetworkManager::processJson(QString json)
{
//log("Json received : " + json);
// Parse main parts of the message (type and body)
QJsonDocument doc; doc = doc.fromJson(json.toUtf8());
QString type = doc.object().take("type").toString();
QJsonValue body = doc.object().take("body");
// Routing messages by type
if ( type == "hbAck" ){
emit hearthbeatReceived(body.toString());
}
else if ( type == "setVariable" ){
QString variable = body.toObject().take("variable").toString();
QString option = body.toObject().take("option").toString();
QString json = QJsonDocument( body.toObject().take("value").toObject() ).toJson();
emit systemVariableChanged(variable, option, json);
}
else if ( type == "call" ){
QString module = body.toObject().take("module").toString();
QString function = body.toObject().take("function").toString();
if (function == "")
function = body.toObject().take("fct").toString();
QString params = QJsonDocument( body.toObject().take("param").toArray() ).toJson();
emit callRequest(module, function, params);
}
else if ( type == "ssid" ){
setssid(body.toString());
setLoggedState(true);
}
else if ( type == "login-error" ){
log("Login error : " + body.toString());
setLoggedState(false);
}
else if ( type == "error"){
log("Server error : " + body.toString());
}
else{
emit jsonReceived(type, body);
emit jsonStringReceived(json);
}
}
示例11: QJsonDocument
char *toString(const QJsonValue &value)
{
QByteArray ret;
if (value.isObject())
ret = QJsonDocument(value.toObject()).toJson();
else if (value.isArray())
ret = QJsonDocument(value.toArray()).toJson();
else
ret = value.toString().toLatin1();
return qstrdup(ret.data());
}
示例12: callbackParams
void Ledger::send(const QString& endpoint, const QString& success, const QString& fail, QNetworkAccessManager::Operation method, AccountManagerAuth::Type authType, QJsonObject request) {
auto accountManager = DependencyManager::get<AccountManager>();
const QString URL = "/api/v1/commerce/";
JSONCallbackParameters callbackParams(this, success, this, fail);
qCInfo(commerce) << "Sending" << endpoint << QJsonDocument(request).toJson(QJsonDocument::Compact);
accountManager->sendRequest(URL + endpoint,
authType,
method,
callbackParams,
QJsonDocument(request).toJson());
}
示例13: exportToJsonString
QString Var::exportToJsonString()
{
QJsonDocument doc;
if(getType()=="string")
return this->exportToJson().toString();
if(getType()=="map")
doc=QJsonDocument(this->exportToJson().toObject());
if(getType()=="list")
doc=QJsonDocument(this->exportToJson().toArray());
return doc.toJson();
}
示例14: QJsonDocument
QByteArray NJson::stringify(QJsonDocument::JsonFormat format) const
{
QJsonDocument doc;
if (mRootValue.isArray()) {
doc = QJsonDocument(mRootValue.toArray());
} else {
doc = QJsonDocument(mRootValue.toObject());
}
return doc.toJson(format);
}
示例15: conf
void Utils::saveConfig()
{
QFile conf("./Config.txt");
conf.open(QIODevice::WriteOnly|QIODevice::Text);
conf.write(QJsonDocument(config).toJson());
conf.close();
}