本文整理汇总了C++中QJsonDocument函数的典型用法代码示例。如果您正苦于以下问题:C++ QJsonDocument函数的具体用法?C++ QJsonDocument怎么用?C++ QJsonDocument使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了QJsonDocument函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
);
}
开发者ID:audifaxdev,项目名称:QRestClient,代码行数:33,代码来源:qrestclient.cpp
示例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);
}
开发者ID:ghjinlei,项目名称:qt5,代码行数:39,代码来源:qjsondocument.cpp
示例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());
}
}
开发者ID:c-toolbox,项目名称:C-Troll,代码行数:27,代码来源:application.cpp
示例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);
}
开发者ID:jabouzi,项目名称:qt,代码行数:28,代码来源:mainwindow.cpp
示例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));
}
开发者ID:PhiTheta,项目名称:stellarium,代码行数:28,代码来源:LocationService.cpp
示例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;
}
开发者ID:hbirchtree,项目名称:jason,代码行数:29,代码来源:jsonparser.cpp
示例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");
}
}
开发者ID:PhiTheta,项目名称:stellarium,代码行数:60,代码来源:ScriptService.cpp
示例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;
}
开发者ID:alexeyhyn,项目名称:laravel,代码行数:35,代码来源:mnetworkmanager.cpp
示例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");
}
}
开发者ID:PhiTheta,项目名称:stellarium,代码行数:56,代码来源:LocationSearchService.cpp
示例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);
}
}
开发者ID:think-free,项目名称:QtHelpers,代码行数:55,代码来源:networkmanager.cpp
示例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());
}
开发者ID:KDE,项目名称:discover,代码行数:11,代码来源:SnapTest.cpp
示例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());
}
开发者ID:SeijiEmery,项目名称:hifi,代码行数:11,代码来源:Ledger.cpp
示例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();
}
开发者ID:Aspenka,项目名称:SSD,代码行数:11,代码来源:var.cpp
示例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);
}
开发者ID:h13i32maru,项目名称:navyjs-legacy2,代码行数:11,代码来源:n_json.cpp
示例15: conf
void Utils::saveConfig()
{
QFile conf("./Config.txt");
conf.open(QIODevice::WriteOnly|QIODevice::Text);
conf.write(QJsonDocument(config).toJson());
conf.close();
}
开发者ID:sanniu,项目名称:BiliLocal,代码行数:7,代码来源:Utils.cpp
示例16: SETTING
bool OwnCloudNetworkFactory::renameFeed(const QString &new_name, int feed_id) {
QString final_url = m_urlRenameFeed.arg(QString::number(feed_id));
QByteArray result_raw;
QJsonObject json;
json["feedTitle"] = new_name;
NetworkResult network_reply = NetworkFactory::performNetworkOperation(final_url,
qApp->settings()->value(GROUP(Feeds),
SETTING(Feeds::UpdateTimeout)).toInt(),
QJsonDocument(json).toJson(QJsonDocument::Compact),
QSL("application/json"), result_raw,
QNetworkAccessManager::PutOperation,
true, m_authUsername, m_authPassword,
true);
m_lastError = network_reply.first;
if (network_reply.first != QNetworkReply::NoError) {
qWarning("ownCloud: Renaming of feed failed with error %d.", network_reply.first);
return false;
}
else {
return true;
}
}
开发者ID:keinkurt,项目名称:rssguard,代码行数:25,代码来源:owncloudnetworkfactory.cpp
示例17: QJsonDocument
bool FileManager::saveToFile( QString path, QString categoryPath, QList<TrackModel*> trackModels )
{
QJsonObject jsonObject;
QJsonArray trackArray;
for ( int i = 0; i < trackModels.size(); i++ )
trackArray.append( trackModels[i]->serializeToJson() );
// Put into json document
jsonObject["categoryPath"] = categoryPath;
jsonObject["tracks"] = trackArray;
QJsonDocument jsonDoc = QJsonDocument( jsonObject );
// Prep file
QFile file;
file.setFileName( path );
// Open
if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) )
return false;
// Write
int result = file.write( jsonDoc.toJson() );
qDebug() << "...wrote" << result << "bytes to" << path;
return result != -1;
}
开发者ID:jcelerier,项目名称:Prism,代码行数:27,代码来源:FileManager.cpp
示例18: makeJsonpStart
// returns null array on error
QByteArray makeJsonpStart(int code, const QByteArray &reason, const HttpHeaders &headers)
{
QByteArray out = "/**/" + jsonpCallback + "(";
if(jsonpExtendedResponse)
{
QByteArray reasonJson = serializeJsonString(QString::fromUtf8(reason));
if(reasonJson.isNull())
return QByteArray();
QVariantMap vheaders;
foreach(const HttpHeader h, headers)
{
if(!vheaders.contains(h.first))
vheaders[h.first] = h.second;
}
QByteArray headersJson = QJsonDocument(QJsonObject::fromVariantMap(vheaders)).toJson(QJsonDocument::Compact);
if(headersJson.isNull())
return QByteArray();
out += "{\"code\": " + QByteArray::number(code) + ", \"reason\": " + reasonJson + ", \"headers\": " + headersJson + ", \"body\": \"";
}
return out;
}
开发者ID:mcspring,项目名称:pushpin,代码行数:27,代码来源:requestsession.cpp
示例19: mml2
void MainWindow::loadthreadfromeinternet()
{
MyMutexLocker mml2("mainwindowtest1",1000);
if (!mml2.success()) return;
clearAll();
//322 383 359 390
//403
//391
//454 278 387 415 366 385 368 402 307 405
// add 371
int a[17] = {322, 383, 359, 390, 403, 391, 454, 278, 387, 415, 366, 385, 368, 402, 307, 405, 371};
for (int i=0; i<17; i++) {
//if (a[i] == 359) continue; // jiuwen bucha
QString s = "forum";
s+=QString::number(a[i]);
s+=".txt";
QJsonDocument jd;
FileCenter::load(s, jd);
SisThread::read( jd.array());
SisThread::getOneForum(QString::number(a[i]));
QJsonArray aa;
SisThread::write(aa);
FileCenter::save(s, QJsonDocument(aa));
clearAll();
}
}
开发者ID:xh286286,项目名称:sisvisit,代码行数:26,代码来源:mainwindow.cpp
示例20: memcpy
int OctreeQuery::getBroadcastData(unsigned char* destinationBuffer) {
unsigned char* bufferStart = destinationBuffer;
// back a boolean (cut to 1 byte) to designate if this query uses the sent view frustum
memcpy(destinationBuffer, &_usesFrustum, sizeof(_usesFrustum));
destinationBuffer += sizeof(_usesFrustum);
if (_usesFrustum) {
// TODO: DRY this up to a shared method
// that can pack any type given the number of bytes
// and return the number of bytes to push the pointer
// camera details
memcpy(destinationBuffer, &_cameraPosition, sizeof(_cameraPosition));
destinationBuffer += sizeof(_cameraPosition);
destinationBuffer += packOrientationQuatToBytes(destinationBuffer, _cameraOrientation);
destinationBuffer += packFloatAngleToTwoByte(destinationBuffer, _cameraFov);
destinationBuffer += packFloatRatioToTwoByte(destinationBuffer, _cameraAspectRatio);
destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraNearClip);
destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraFarClip);
memcpy(destinationBuffer, &_cameraEyeOffsetPosition, sizeof(_cameraEyeOffsetPosition));
destinationBuffer += sizeof(_cameraEyeOffsetPosition);
}
// desired Max Octree PPS
memcpy(destinationBuffer, &_maxQueryPPS, sizeof(_maxQueryPPS));
destinationBuffer += sizeof(_maxQueryPPS);
// desired voxelSizeScale
memcpy(destinationBuffer, &_octreeElementSizeScale, sizeof(_octreeElementSizeScale));
destinationBuffer += sizeof(_octreeElementSizeScale);
// desired boundaryLevelAdjust
memcpy(destinationBuffer, &_boundaryLevelAdjust, sizeof(_boundaryLevelAdjust));
destinationBuffer += sizeof(_boundaryLevelAdjust);
memcpy(destinationBuffer, &_cameraCenterRadius, sizeof(_cameraCenterRadius));
destinationBuffer += sizeof(_cameraCenterRadius);
// create a QByteArray that holds the binary representation of the JSON parameters
QByteArray binaryParametersDocument;
if (!_jsonParameters.isEmpty()) {
binaryParametersDocument = QJsonDocument(_jsonParameters).toBinaryData();
}
// write the size of the JSON parameters
uint16_t binaryParametersBytes = binaryParametersDocument.size();
memcpy(destinationBuffer, &binaryParametersBytes, sizeof(binaryParametersBytes));
destinationBuffer += sizeof(binaryParametersBytes);
// pack the binary JSON parameters
// NOTE: for now we assume that the filters that will be set are all small enough that we will not have a packet > MTU
if (binaryParametersDocument.size() > 0) {
memcpy(destinationBuffer, binaryParametersDocument.data(), binaryParametersBytes);
destinationBuffer += binaryParametersBytes;
}
return destinationBuffer - bufferStart;
}
开发者ID:cozza13,项目名称:hifi,代码行数:60,代码来源:OctreeQuery.cpp
注:本文中的QJsonDocument函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论