コード例 #1
0
ファイル: qjsonvalue.cpp プロジェクト: softnhard/QJSON
/*!
    Converts the value to an object and returns it.

    If type() is not Object, a QJsonObject() will be returned.
 */
QJsonObject QJsonValue::toObject() const
{
    if (!d || t != Object)
        return QJsonObject();

    return QJsonObject(d, static_cast<QJsonPrivate::Object *>(base));
}
コード例 #2
0
void LogSelectorForm::check_config(){
    QString conf_path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation).append("/config.json");

    QFile f(conf_path);

    if (!f.exists()){
        QDir().mkpath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation));
        QJsonValue algorithm("KMeans");
        QJsonObject param = QJsonObject();
        param.insert("n_clusters",4);
        QJsonArray features;
        features.append(QString("count_domain_with_numbers"));
        features.append(QString("average_domain_length"));
        features.append(QString("std_domain_length"));
        features.append(QString("count_request"));
        features.append(QString("average_requisition_degree"));
        features.append(QString("std_requisition_degree"));
        features.append(QString("minimum_requisition_degree"));
        QJsonObject target = QJsonObject();
        target.insert("algorithm",algorithm);
        target.insert("features",features);
        target.insert("param",param);
        QJsonDocument config_out(target);
        QFile out_file(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation).append("/config.json"));
        out_file.open(QIODevice::WriteOnly | QIODevice::Text);
        out_file.write(config_out.toJson());
        out_file.close();
    }
}
コード例 #3
0
ファイル: qjsondocument.cpp プロジェクト: ghjinlei/qt5
/*!
    Returns the QJsonObject contained in the document.

    Returns an empty object if the document contains an
    array.

    \sa isObject(), array(), setObject()
 */
QJsonObject QJsonDocument::object() const
{
    if (d) {
        QJsonPrivate::Base *b = d->header->root();
        if (b->isObject())
            return QJsonObject(d, static_cast<QJsonPrivate::Object *>(b));
    }
    return QJsonObject();
}
コード例 #4
0
ファイル: qjsonobject.cpp プロジェクト: 2gis/2gisqt5android
/*!
    Converts the variant map \a map to a QJsonObject.

    The keys in \a map will be used as the keys in the JSON object,
    and the QVariant values will be converted to JSON values.

    \sa fromVariantHash(), toVariantMap(), QJsonValue::fromVariant()
 */
QJsonObject QJsonObject::fromVariantMap(const QVariantMap &map)
{
    QJsonObject object;
    if (map.isEmpty())
        return object;

    object.detach2(1024);

    QVector<QJsonPrivate::offset> offsets;
    QJsonPrivate::offset currentOffset;
    currentOffset = sizeof(QJsonPrivate::Base);

    // the map is already sorted, so we can simply append one entry after the other and
    // write the offset table at the end
    for (QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it) {
        QString key = it.key();
        QJsonValue val = QJsonValue::fromVariant(it.value());

        bool latinOrIntValue;
        int valueSize = QJsonPrivate::Value::requiredStorage(val, &latinOrIntValue);

        bool latinKey = QJsonPrivate::useCompressed(key);
        int valueOffset = sizeof(QJsonPrivate::Entry) + QJsonPrivate::qStringSize(key, latinKey);
        int requiredSize = valueOffset + valueSize;

        if (!object.detach2(requiredSize + sizeof(QJsonPrivate::offset))) // offset for the new index entry
            return QJsonObject();

        QJsonPrivate::Entry *e = reinterpret_cast<QJsonPrivate::Entry *>(reinterpret_cast<char *>(object.o) + currentOffset);
        e->value.type = val.t;
        e->value.latinKey = latinKey;
        e->value.latinOrIntValue = latinOrIntValue;
        e->value.value = QJsonPrivate::Value::valueToStore(val, (char *)e - (char *)object.o + valueOffset);
        QJsonPrivate::copyString((char *)(e + 1), key, latinKey);
        if (valueSize)
            QJsonPrivate::Value::copyData(val, (char *)e + valueOffset, latinOrIntValue);

        offsets << currentOffset;
        currentOffset += requiredSize;
        object.o->size = currentOffset;
    }

    // write table
    object.o->tableOffset = currentOffset;
    if (!object.detach2(sizeof(QJsonPrivate::offset)*offsets.size()))
        return QJsonObject();
    memcpy(object.o->table(), offsets.constData(), offsets.size()*sizeof(uint));
    object.o->length = offsets.size();
    object.o->size = currentOffset + sizeof(QJsonPrivate::offset)*offsets.size();

    return object;
}
コード例 #5
0
QJsonObject DCMotor::getDirectionJson()
{
    QJsonValue jsonDir(dirn);
    return QJsonObject({
                           QPair<QString, QJsonValue>(directionKey, jsonDir)
                       });
}
コード例 #6
0
ファイル: qjsonvalue.cpp プロジェクト: venkatarajasekhar/Qt
/*!
    Converts the value to an object and returns it.

    If type() is not Object, the \a defaultValue will be returned.
 */
QJsonObject QJsonValue::toObject(const QJsonObject &defaultValue) const
{
    if (!d || t != Object)
        return defaultValue;

    return QJsonObject(d, static_cast<QJsonPrivate::Object *>(base));
}
コード例 #7
0
ファイル: utils.cpp プロジェクト: Martchus/videodownloader
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();
}
コード例 #8
0
QJsonObject DCMotor::getPwmJson()
{
    QJsonValue jsonPWM(pwmValue);
    return QJsonObject({
                           QPair<QString, QJsonValue>(pwmKey, jsonPWM)
                       });
}
コード例 #9
0
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;
}
コード例 #10
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();
    */
}
コード例 #11
0
ファイル: BookmarksModel.cpp プロジェクト: kglowins/DREAM3D
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
BookmarksModel* BookmarksModel::NewInstanceFromFile(QString filePath)
{
  QFileInfo fi(filePath);
  if (fi.exists() & fi.isFile())
  {
    // Erase the old content
    if (self)
    {
      delete self;
      self = NULL;
    }

    DREAM3DSettings prefs(filePath);

    prefs.beginGroup("DockWidgetSettings");
    prefs.beginGroup("Bookmarks Dock Widget");
    QJsonObject modelObj = prefs.value("Bookmarks Model", QJsonObject());
    prefs.endGroup();
    prefs.endGroup();

    self = BookmarksTreeView::FromJsonObject(modelObj);
  }

  return self;
}
コード例 #12
0
ファイル: dbmodel.cpp プロジェクト: ndesai/pioneer-av-remote
DbModel::DbModel(QQuickItem *parent) :
    QAbstractListModel(parent),
    m_status(Null),
    m_schema(QJsonObject()),
    m_mapDepth(0),
    m_jsonDbPath("")
{
    DEBUG;

    //    QFile db(DBPATH);
    //    if(!db.open(QIODevice::ReadOnly))
    //    {
    //        qDebug() << "db does not exist! creating/copying...";
    //        QFile file("assets:/qml/MyCollections/db/store.db");
    //        file.copy(DBPATH);
    //    } else
    //    {
    //        qDebug() << "Successfully opened db, hash is below:";
    //        QByteArray hashData = QCryptographicHash::hash(db.readAll(),QCryptographicHash::Md5);
    //        qDebug() << hashData.toHex();
    //    }
    //    db.close();


    connect(this, SIGNAL(nameChanged(QString)),
            this, SLOT(openDatabase()));
    connect(this, SIGNAL(schemaChanged(QJsonObject)),
            this, SLOT(buildDataTables(QJsonObject)));
}
コード例 #13
0
ファイル: tst_webchannel.cpp プロジェクト: RobinWuDev/Qt
void TestWebChannel::testDisconnect()
{
    QWebChannel channel;
    channel.connectTo(m_dummyTransport);
    channel.disconnectFrom(m_dummyTransport);
    m_dummyTransport->emitMessageReceived(QJsonObject());
}
コード例 #14
0
ファイル: user.cpp プロジェクト: KasaiDot/Shinjiru
User *User::remake() {
  QJsonObject result = API::sharedAPI()
                           ->sharedAniListAPI()
                           ->get(API::sharedAPI()->sharedAniListAPI()->API_USER)
                           .object();

  if (result == QJsonObject()) return User::sharedUser();

  QString profile_image = result.value("image_url_med").toString();

  this->setDisplayName(result.value("display_name").toString());
  this->setScoreType(result.value("score_type").toInt());
  this->setTitleLanguage(result.value("title_language").toString());
  this->setAnimeTime(result.value("anime_time").toInt());
  this->setCustomLists(
      result.value("custom_list_anime").toArray().toVariantList());
  this->setNotificationCount(result.value("notifications").toInt());

  if (this->profile_image_url != profile_image) {
    this->setProfileImageURL(profile_image);
    this->loadProfileImage();
  }

  this->fetchUpdatedList();

  return User::sharedUser();
}
コード例 #15
0
ファイル: model_item.cpp プロジェクト: jeyboy/palyo2
QJsonObject ModelItem::toJSON() {
    QJsonObject root = QJsonObject();

    root["t"] = title;
    root["s"] = state -> getFuncValue();
    root["p"] = path;

    if (!info.isEmpty())
        root["a"] = info;

    if (bpm != 0)
        root["m"] = bpm;

    if (size != -1)
        root["b"] = size;

    if (genreID != -1)
        root["g"] = genreID;

    if (!duration.isEmpty())
        root["d"] = duration;

    if (!extension.isNull())
        root["e"] = extension;

    return root;
}
コード例 #16
0
void WebRequest::replyFinished(QNetworkReply* reply)
{
    if(reply == nullptr)
        return;

    mtxCallback.lock();
    CallbackReply callback = mapCallback[reply];
    mapCallback.remove(reply);
    mtxCallback.unlock();

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray raw = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(raw);
        if(doc.isArray())
        {
            QJsonObject obj;
            obj["array"] = doc.array();
            callback(obj);
        }
        else
        {
            callback(doc.object());
        }
    }
    else
    {
        callback(QJsonObject());
    }

    reply->deleteLater();
}
コード例 #17
0
QJsonValue GitCloneStep::toJson() const
{
	return QJsonObject({
						   qMakePair(QStringLiteral("type"), type()),
						   qMakePair(QStringLiteral("url"), Json::toJson(m_url))
					   });
}
コード例 #18
0
QJsonObject Scene::serialize() const
{
    QJsonObject scene = QJsonObject();

    // When adding the character list, just add the character
    // IDs to avoid redundancy.

    QJsonArray jCharacters = QJsonArray(),
            jPovCharacters = QJsonArray();

    for (Character *c : mCharacters)
        jCharacters.append(c->id().toString());

    for (Character *c : mPovCharacters)
        jPovCharacters.append(c->id().toString());

    scene[JSON_HEADLINE] = mHeadline;
    scene[JSON_ACTION] = mAction;
    scene[JSON_CHARACTERS] = jCharacters;
    scene[JSON_POV_CHARACTERS] = jPovCharacters;
    scene[JSON_ID] = id().toString();
    if (mPlotline)
        scene.insert(JSON_PLOTLINE, QJsonValue(mPlotline->id().toString()));

    return scene;
}
コード例 #19
0
QJsonObject QJsonValueProto::toObject() const
{
  QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject());
  if (item)
    return item->toObject();
  return QJsonObject();
}
コード例 #20
0
ファイル: n_json.cpp プロジェクト: h13i32maru/navyjs-legacy2
void NJson::clear() {
    if (mRootValue.isArray()) {
        mRootValue = QJsonValue(QJsonArray());
    } else {
        mRootValue = QJsonValue(QJsonObject());
    }
}
コード例 #21
0
ファイル: Transform.cpp プロジェクト: JamesLinus/hifi
QJsonObject Transform::toJson(const Transform& transform) {
    if (transform.isIdentity()) {
        return QJsonObject();
    }

    QJsonObject result;
    if (transform.getTranslation() != vec3()) {
        auto json = toJsonValue(transform.getTranslation());
        if (!json.isNull()) {
            result[JSON_TRANSLATION] = json;
        }
    }

    if (transform.getRotation() != quat()) {
        auto json = toJsonValue(transform.getRotation());
        if (!json.isNull()) {
            result[JSON_ROTATION] = json;
        }
    }

    if (transform.getScale() != vec3(1.0f)) {
        auto json = toJsonValue(transform.getScale());
        if (!json.isNull()) {
            result[JSON_SCALE] = json;
        }
    }
    return result;
}
コード例 #22
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));
}
コード例 #23
0
void AuthorizationManager::ListCertificates(QString token, QJsonObject *out){
  QStringList keys; //Format: "RegisteredCerts/<user>/<key>"
  if( hasFullAccess(token) ){ 
    //Read all user's certs
    keys = CONFIG->allKeys().filter("RegisteredCerts/");
    //qDebug() << "Found SSL Keys to List:" << keys;
  }else{
    //Only list certs for current user
    QString cuser = hashID(token).section("::::",2,2);
    keys = CONFIG->allKeys().filter("RegisteredCerts/"+cuser+"/");
    //qDebug() << "Found SSL Keys to List:" << keys;
  }
  keys.sort();
  //Now put the known keys into the output structure arranged by username/key
  QJsonObject user; QString username;
  for(int i=0; i<keys.length(); i++){
    if(username!=keys[i].section("/",1,1)){
      if(!user.isEmpty()){ out->insert(username, user); user = QJsonObject(); } //save the current info to the output
      username = keys[i].section("/",1,1); //save the new username for later
    }
    QString info = CONFIG->value(keys[i]).toString();
    QString key = keys[i].section("/",2,-1);//just in case the key has additional "/" in it
    user.insert(key,info);
  }
  if(!user.isEmpty() && !username.isEmpty()){ out->insert(username, user); }
}
コード例 #24
0
ファイル: diceapi.cpp プロジェクト: olehpidhi/DiceAPI
DiceAPI::DiceAPI(QObject *parent):
    QObject(parent),
    token(QString()),
    JSONReply(QJsonObject())
{
    connect(&mgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyRecieved(QNetworkReply*)));
}
コード例 #25
0
ファイル: diceapi.cpp プロジェクト: olehpidhi/DiceAPI
DiceAPI::DiceAPI(QString pToken, QObject *parent):
    QObject(parent),
    token(pToken),
    JSONReply(QJsonObject())
{
    connect(&mgr, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this, SLOT(setCredentials(QNetworkReply*,QAuthenticator*)));
}
コード例 #26
0
ファイル: diary.cpp プロジェクト: mariosgn/nunc
bool Diary::create()
{
    QString diaryPath = ms_DiaryPath;

    QFileInfo p(diaryPath);

    if ( p.isFile() )
    {
        errorMsg( QString( tr("%1 already exists: please insert a not existing path") ).arg(diaryPath) );
        return false;
    }

    if ( !p.isDir() )
    {
        errorMsg( QString( tr( "%1 does not exists: please insert an existing and writable path").arg(diaryPath) ) );
        return false;
    }

    ms_ConfFileName = DEFAULT_CONF_FILE;

    ms_ConfObject = QJsonObject();
    ms_ConfObject.insert( CONF_NUNC, true );

    if ( ! writeConf()  )
        return false;

    createCurrentEntry();
    updateEntriesIdx();

    return true;
}
コード例 #27
0
ファイル: sessionrequest.cpp プロジェクト: Novynn/Adamant
void Session::Request::onAccountStashTabsResult() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
    QByteArray response;
    if (reply->error()) {
        const QString errorMessage = QString("Network error in %1: %2").arg(__FUNCTION__).arg(reply->errorString());
        Session::LogError(errorMessage);
        QJsonObject error({
            {
                "error", QJsonObject({
                    {"message", errorMessage},
                    {"internal", true}
                })
            }
        });
        response = QJsonDocument(error).toJson();
    }
    else {
        response = reply->readAll();
    }

    QNetworkRequest request = reply->request();
    QVariant data = getAttribute(&request, UserData);
    QString league = getAttribute(&request, League).toString();

    emit accountStashTabs(league, response, data);
    QJsonDocument doc = QJsonDocument::fromJson(response);
    emit accountStashTabsJson(league, doc, data);

    reply->deleteLater();
}
コード例 #28
0
tMessage JsonMsgBuilder::ConsructMsg()
{
    QJsonDocument doc(mMsgObject);
    tMessage msg(doc.toJson(QJsonDocument::Indented));
    mMsgObject = QJsonObject();
    return msg;
}
コード例 #29
0
ファイル: RPCMiner.cpp プロジェクト: Neozaru/bitmonero-qt
void RPCMiner::getMiningStatus() {
    JsonRPCRequest* lReq = rpc.sendRequest("mining_status", QJsonObject(), true);

    QObject::connect(lReq,&JsonRPCRequest::jsonResponseReceived,[this](const QJsonObject pJsonResponse) {

//        qDebug() << "'mining_status' Response : " << pJsonResponse;
        const QString& lStatus = pJsonResponse["status"].toString();

        if ( lStatus == "OK" ) {

            if ( !pJsonResponse["active"].isBool() ||
                 !pJsonResponse["threads_count"].isDouble() ||
                 !pJsonResponse["address"].isString() ||
                 !pJsonResponse["speed"].isDouble() ) {

                qCritical() << "Invalid data format for 'mining_status' response. Is your Daemon up to date ?";
            }

            this->onGetMiningStatusResponse(
                    pJsonResponse["active"].toBool(),
                    pJsonResponse["threads_count"].toDouble(),
                    pJsonResponse["address"].toString(),
                    pJsonResponse["speed"].toDouble()
                    );
        }
        else {
            qWarning() << "Bad status for mining status : " << lStatus;
        }

    });
}
コード例 #30
0
ファイル: pluginmanager.cpp プロジェクト: Novynn/Adamant
const QJsonObject PluginManager::getPluginMetaData(const AdamantPlugin *plugin) const {
    for (const AdamantPluginInfo* data : _plugins) {
        if (data->instance == plugin) {
            return data->loader->metaData();
        }
    }
    return QJsonObject();
}