void NodeAssociateStore::load()
{
	//qDebug()<<"NodeAssociateStore: Loading from file "<<mFilename;
	QJsonParseError jsonError;
	QByteArray raw=utility::fileToByteArray(mFilename);
	if(raw.size()<1) {
		//Let empty data pass because it is valid the first time app starts
		qWarning() << "WARNING: Data read from file "<<mFilename<< " was empty";
		mReady=true;
	} else {
		QJsonDocument doc = QJsonDocument::fromJson(raw, &jsonError);
		if (QJsonParseError::NoError != jsonError.error) {
			qWarning() << "ERROR: Parsing json data: "<<jsonError.errorString()<< " for data "<<raw<<" from file "<<mFilename;
			mError=true;
		} else {
			//qDebug()<<"PARSED JSON: "<<doc.toJson();
			mPeers.clear();
			QVariantMap map = doc.object().toVariantMap();
			QVariantList peers=map["peers"].toList();
			for(QVariantList::iterator b=peers.begin(), e=peers.end(); b!=e; ++b) {
				QSharedPointer<NodeAssociate> peer=QSharedPointer<NodeAssociate>(new NodeAssociate((*b).toMap()));
				setParticipant(peer);
			}
			mReady=true;
		}
	}
	//qDebug()<<"EMITTING storeReady";
	emit peerStoreReady(!mError);
}
示例#2
0
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;
}
示例#3
0
    virtual void OnObserve(const char* aTopic, const PRUnichar* aData) {
        // LOGT("aTopic: %s, data: %s", aTopic, NS_ConvertUTF16toUTF8(aData).get());
        QString data((QChar*)aData);
        if (!data.startsWith('{') && !data.startsWith('[') && !data.startsWith('"')) {
            QVariant vdata = QVariant::fromValue(data);
            Q_EMIT q->recvObserve(aTopic, vdata);
            return;
        }
        bool ok = true;
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
        QJson::Parser parser;
        QVariant vdata = parser.parse(data.toUtf8(), &ok);
#else
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &error);
        ok = error.error == QJsonParseError::NoError;
        QVariant vdata = doc.toVariant();
#endif
        if (ok) {
            // LOGT("mesg:%s, data:%s", aTopic, data.toUtf8().data());
            Q_EMIT q->recvObserve(aTopic, vdata);
        } else {
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
            LOGT("parse: s:'%s', err:%s, errLine:%i", data.toUtf8().data(), parser.errorString().toUtf8().data(), parser.errorLine());
#else
            LOGT("parse: s:'%s', err:%s, errLine:%i", data.toUtf8().data(), error.errorString().toUtf8().data(), error.offset);
#endif
        }
    }
示例#4
0
AnimNode::Pointer AnimNodeLoader::load(const QByteArray& contents, const QUrl& jsonUrl) {

    // convert string into a json doc
    QJsonParseError error;
    auto doc = QJsonDocument::fromJson(contents, &error);
    if (error.error != QJsonParseError::NoError) {
        qCCritical(animation) << "AnimNodeLoader, failed to parse json, error =" << error.errorString();
        return nullptr;
    }
    QJsonObject obj = doc.object();

    // version
    QJsonValue versionVal = obj.value("version");
    if (!versionVal.isString()) {
        qCCritical(animation) << "AnimNodeLoader, bad string \"version\"";
        return nullptr;
    }
    QString version = versionVal.toString();

    // check version
    // AJT: TODO version check
    if (version != "1.0" && version != "1.1") {
        qCCritical(animation) << "AnimNodeLoader, bad version number" << version << "expected \"1.0\"";
        return nullptr;
    }

    // root
    QJsonValue rootVal = obj.value("root");
    if (!rootVal.isObject()) {
        qCCritical(animation) << "AnimNodeLoader, bad object \"root\"";
        return nullptr;
    }

    return loadNode(rootVal.toObject(), jsonUrl);
}
示例#5
0
文件: Json.cpp 项目: xtuer/Qt
JsonPrivate::JsonPrivate(const QString &jsonOrJsonFilePath, bool fromFile) {
    QByteArray json("{}"); // json 的内容

    // 如果传人的是 Json 文件的路径,则读取内容
    if (fromFile) {
        QFile file(jsonOrJsonFilePath);

        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            json = file.readAll();
        } else {
            qDebug() << QString("Cannot open the file: %1").arg(jsonOrJsonFilePath);
        }
    } else {
        json = jsonOrJsonFilePath.toUtf8();
    }

    // 解析 Json
    QJsonParseError error;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(json, &error);
    root = jsonDocument.object();

    if (QJsonParseError::NoError != error.error) {
        qDebug() << error.errorString() << ", Offset: " << error.offset;
    }
}
示例#6
0
Shop* AdamantShopPlugin::loadShop(const QString &file) {
    QFile shopFile(file);
    if (shopFile.exists() && shopFile.open(QFile::ReadOnly)) {
        Shop* shop = new Shop();

        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(shopFile.readAll(), &error);
        if (error.error == QJsonParseError::NoError && shop->load(doc.object())) {
            qDebug() << "Loaded shop: " << shop->league() << file;
        }
        else {
            qDebug() << "Failed to load shop: " << file << error.errorString();
            shop->deleteLater();
            shop = nullptr;
        }
        shopFile.close();

        if (shop != nullptr) {
            saveShop(shop);
        }
        return shop;
    }

    return nullptr;
}
bool IndigoMenuBar::loadSettings()
{


    QFile loadFile(QStringLiteral("data/navigation.json"));

    if (!loadFile.open(QIODevice::ReadOnly)) {
        qWarning("Couldn't open menubarfile.");
        return false;
    }

    QByteArray data = loadFile.readAll();

    qDebug() << "data" << data << endl;

    QJsonParseError jerror;
    QJsonDocument loadDoc(QJsonDocument::fromJson(data, &jerror));
    if(jerror.error != QJsonParseError::NoError) {
        qWarning("Error while parsing json.");
        qDebug() << jerror.errorString() << endl;
        qDebug() << "error at" << QTextCodec::codecForMib(106)->toUnicode(data).mid(jerror.offset - 1, 20) << endl;
        return false;
    }
    read(loadDoc.object());
    return true;
}
示例#8
0
Cockpit::Cockpit(bool overlay):overlay(overlay)


    {


        QFile sf(SETTINGSFILE);
        sf.open(QIODevice::ReadOnly | QIODevice::Text);
        QJsonParseError e;
        settings = QJsonDocument::fromJson(sf.readAll(), &e);
        cout << e.errorString().toStdString()<<endl;

        Settings* s = new Settings(settings.object(), this,overlay);
        this->setCentralWidget(s);

        sf.close();



        QObject::connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(savesettings()));





    }
示例#9
0
bool CharactersManager::loadCharacters()
{
    const QString path = QStandardPaths::locate(QStandardPaths::StandardLocation::DataLocation,
                                                QStringLiteral(JS_FILE),
                                                QStandardPaths::LocateOption::LocateFile);

    QFile loadFile(path);

    if(!loadFile.open(QFile::OpenModeFlag::ReadOnly))
    {
        qWarning("Can't load file");
        return false;
    }

    QByteArray byteArray = loadFile.readAll();
    QJsonParseError error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(byteArray, &error));

    if(error.error != QJsonParseError::ParseError::NoError)
    {
        qWarning("Can't read json object");
        qWarning() << error.errorString();
        return false;
    }

    this->readCharacters(jsonDoc.object());

    return true;
}
示例#10
0
void ApiCommunicator::_sendRequest(const QUrl &url, void (ApiCommunicator::*signal)(const QJsonObject &) const) const
{
  qDebug() << "GET" << url.toString();
  QNetworkReply *reply = _nam->get(QNetworkRequest(url));
  connect(reply, &QNetworkReply::readChannelFinished, [=]() {
    if (reply->error()) {
      qDebug() << "Request error:" << reply->errorString();
      return;
    }
    const QByteArray data = reply->readAll();
    reply->deleteLater();
    if (data.size() <= 1)
      return;
    qDebug() << "GET" << url.toString() << ">>" << data;

    QJsonParseError parseError;
    const QJsonObject json = QJsonDocument::fromJson(data, &parseError).object();
    if (parseError.error)
      qDebug() << "JSON parse error:" << parseError.errorString();
    else {
      emit (this->*signal)(json);
      emit dataFetched(json);
    }
  });
}
示例#11
0
const QJsonObject& HttpRequest::getJson() const
{
  if(!m_Json.isEmpty())
  {
    return m_Json;
  }

  const QByteArray& body = m_Request->get_body();
  auto openBrace = body.indexOf("{");
  auto closeBrace = body.lastIndexOf("}");

  if(openBrace >= 0 && closeBrace >= 0)
  {
    QJsonParseError error;
    m_Json = Utils::toJson(body, &error);

    if(error.error != QJsonParseError::NoError)
    {
      // This should probably be muted later.
      LOG_WARN(error.errorString());
      m_Json = Utils::toJson(QByteArray("{}"));
    }
  }

  QList<QPair<QString, QString> > list = getQuery().queryItems();
  for(auto i = list.begin(); i != list.end(); ++i)
  {
    m_Json.insert(i->first, i->second);
  }

  return m_Json;
}
示例#12
0
void CBDS::loadViewers()
{
    QFile f(QApplication::applicationDirPath() + "/Viewers.json");
    if (f.exists())
    {
        if (f.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QJsonParseError pe;
            QVariantList json = QJsonDocument::fromJson(f.readAll(), &pe).toVariant().toList();
            f.close();
            if (pe.error == QJsonParseError::NoError)
                parseViewerData(json);
            else
                emit error("Failed to parse Viewers.json: " + pe.errorString());
        }
        else
            emit error("Can't open file: " + f.fileName());
    }

    if (!m_viewers.rowCount(QModelIndex()))
    {
        Viewer* l = addViewer("llua", 0, 0, 0, 1, 'c');
        l->setRoomOwner(true);
        setRoomOwner("llua");
    }
}
示例#13
0
Bundle Bundle::fromPath(const QString &path)
{
    Bundle bundle;

    QFileInfo bundlePath(path);
    if (!bundlePath.isReadable()) {
        qCWarning(l) << "bundle" << bundlePath.absolutePath() << "is not readable";
        return Bundle();
    }

    bundle.b->path = path;

    QScopedPointer<QIODevice> manifestJSON(bundle.openFile(Bundle::MANIFEST, QIODevice::Text));
    if (!manifestJSON) {
        qCWarning(l) << "cannot find" << path << "manifest json";
        return Bundle();
    }

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(manifestJSON->readAll(), &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qCWarning(l) << "cannot parse" << path << "manifest json" << parseError.errorString();
        return Bundle();
    }
    manifestJSON->close();
    bundle.b->manifest = doc.object();

    bundle.b->isValid = true;
    return bundle;
}
示例#14
0
Query *Query::fromJSON(const QByteArray &json)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(json, &error);
    if (doc.isNull()) {
        qWarning() << "Could not parse json query" << error.errorString();
        return 0;
    }

    QVariantMap result = doc.toVariant().toMap();
    const QString type = result[QStringLiteral("type")].toString().toLower();
    if (type != QLatin1String("contact")) {
        qWarning() << "Can only handle contact queries";
        return 0;
    }

    ContactQuery *cq = new ContactQuery();
    cq->matchName(result[QStringLiteral("name")].toString());
    cq->matchNickname(result[QStringLiteral("nick")].toString());
    cq->matchEmail(result[QStringLiteral("email")].toString());
    cq->matchUID(result[QStringLiteral("uid")].toString());
    cq->match(result[QStringLiteral("$")].toString());

    const QString criteria = result[QStringLiteral("matchCriteria")].toString().toLower();
    if (criteria == QLatin1String("exact")) {
        cq->setMatchCriteria(ContactQuery::ExactMatch);
    } else if (criteria == QLatin1String("startswith")) {
        cq->setMatchCriteria(ContactQuery::StartsWithMatch);
    }

    cq->setLimit(result[QStringLiteral("limit")].toInt());

    return cq;
}
示例#15
0
void RtCmdClient::requestCommands()
{
    //No commands are present -> thats why help has to be send using a self created command
    const QString help("help");
    const QString description("");
    const Command cmdHelp(help, description);
    this->sendCommandJSON(cmdHelp);

    //Clear Commands
    m_commandManager.clear();

    //Receive
    m_qMutex.lock();
    QByteArray t_sJsonCommands = m_sAvailableData.toUtf8();
    m_qMutex.unlock();

    //Parse
    QJsonParseError error;
    QJsonDocument t_jsonDocumentOrigin = QJsonDocument::fromJson(
            t_sJsonCommands, &error);
    if (error.error == QJsonParseError::NoError)
    {
        m_commandManager.insert(t_jsonDocumentOrigin);
//        qDebug() << "Received Commands" << m_commandManager.commandMap().keys();
    }
    else
    {
        qCritical() << "Unable to parse JSON response: " << error.errorString();
    }
}
示例#16
0
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);
}
示例#17
0
void PasteUpload::downloadFinished()
{
	// if the download succeeded
	if (m_reply->error() == QNetworkReply::NetworkError::NoError)
	{
		QByteArray data = m_reply->readAll();
		m_reply.reset();
		QJsonParseError jsonError;
		QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);
		if (jsonError.error != QJsonParseError::NoError)
		{
			emitFailed(jsonError.errorString());
			return;
		}
		if (!parseResult(doc))
		{
			emitFailed(tr("paste.ee returned an error. Please consult the logs for more information"));
			return;
		}
	}
	// else the download failed
	else
	{
		emitFailed(QString("Network error: %1").arg(m_reply->errorString()));
		m_reply.reset();
		return;
	}
	emitSucceeded();
}
示例#18
0
QVariant JsonTranslationService::parseJson(const QByteArray &json)
{
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    QString js;
    js.reserve(json.size() + 2);
    js.append("(").append(QString::fromUtf8(json)).append(")");

    static QScriptEngine engine;
    if (!engine.canEvaluate(js)) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(tr("Can't evaluate JSON data"));
        return QVariant();
    }

    QScriptValue data = engine.evaluate(js);
    if (engine.hasUncaughtException()) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(engine.uncaughtException().toString());
        return QVariant();
    }

    return data.toVariant();
#else
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(json, &err);

    if (err.error != QJsonParseError::NoError) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(err.errorString());
        return QVariant();
    }

    return doc.toVariant();
#endif
}
示例#19
0
void ExtScript::readJsonFilters()
{
    QString fileName = QStandardPaths::locate(
        QStandardPaths::GenericDataLocation,
        QString(
            "awesomewidgets/scripts/awesomewidgets-extscripts-filters.json"));
    qCInfo(LOG_LIB) << "Filters file" << fileName;
    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCWarning(LOG_LIB) << "Could not open" << fileName;
        return;
    }
    QString jsonText = jsonFile.readAll();
    jsonFile.close();

    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonText.toUtf8(), &error);
    if (error.error != QJsonParseError::NoError) {
        qCWarning(LOG_LIB) << "Parse error" << error.errorString();
        return;
    }
    jsonFilters = jsonDoc.toVariant().toMap();

    qCInfo(LOG_LIB) << "Filters" << jsonFilters;
}
bool LoadSaveManager::load(ILoadSave &loadSave)
{
    QFile file {m_configFilePath};
    if (!file.exists()) {
        qCDebug(QLoggingCategory("load-save-manager")) << "Failed to find config file"
                                                       << m_configFilePath;
        return true; // No file, so no config to load
    }

    if (!file.open(QIODevice::ReadOnly)) {
        qCWarning(QLoggingCategory("load-save-manager")) << "Failed to open config file"
                                                         << m_configFilePath;
        return false;
    }
    QJsonParseError error {-1, QJsonParseError::NoError};
    QJsonDocument document {QJsonDocument::fromJson(file.readAll(), &error)};
    file.close();

    if (error.error != QJsonParseError::NoError) {
        qCWarning(QLoggingCategory("load-save-manager")) << "Failed to parse configuration file";
        qCWarning(QLoggingCategory("load-save-manager")) << "Error" << error.errorString();
        return false;
    }

    loadSave.load(document.object());
    return true;
}
示例#21
0
void QQnxFilePicker::handleFilePickerResponse(const char *data)
{
    QJsonParseError jsonError;
    QJsonDocument document = QJsonDocument::fromJson(data, &jsonError);

    if (jsonError.error != QJsonParseError::NoError) {
        qFilePickerDebug() << "Error parsing FilePicker response: "
                 << jsonError.errorString();
        Q_EMIT closed();
        cleanup();
        return;
    }

    // The response is a list of Json objects.
    const QVariantList array = document.array().toVariantList();

    foreach (const QVariant &variant, array) {
        const QJsonObject object = QJsonObject::fromVariantMap(variant.toMap());
        const QUrl url(object.value(QStringLiteral("uri")).toString());
        const QString localFile = url.toLocalFile(); // strip "file://"

        if (!localFile.isEmpty())
            m_selectedFiles << localFile;

        qFilePickerDebug() << "FilePicker uri response:" << localFile;
    }

    Q_EMIT closed();
    cleanup();
}
示例#22
0
void KCTranslator::translationRequestFinished()
{
	// Read the response body
	QNetworkReply *reply(qobject_cast<QNetworkReply*>(QObject::sender()));
	if(reply->error() != QNetworkReply::NoError)
	{
		emit loadFailed(QString("Network Error: %1").arg(reply->errorString()));
		return;
	}
	QByteArray body(reply->readAll());

	// Parse the JSON
	QJsonParseError error;
	QJsonDocument doc(QJsonDocument::fromJson(body, &error));
	if(error.error != QJsonParseError::NoError)
	{
		emit loadFailed(QString("JSON Error: %1").arg(error.errorString()));
		return;
	}
	QJsonObject root(doc.object());

	// Check the response
	int success = (int) root.value("success").toDouble();
	if(success != 1)
	{
		emit loadFailed(QString("API Error %1").arg(success));
		return;
	}

	// Parse the translation data
	translation = root.value("translation").toObject().toVariantMap();

	emit loadFinished();
}
示例#23
0
XSAppBuilder::XSAppBuilder(const QString &projectPath, const QString &projectName)
{
    this->projectPath = projectPath;
    this->projectName = projectName;
    bon = static_cast<xsObject *>(xsObject::createInstance());;
    xsValue val;
    val.type = XS_VALUE_STRING;
    val.data.s = "bon";
    bon->setProperty("id", &val);
    isFirstObject = true;

    QFile transform(":xs_model/models/transform.json");
    if(transform.open(QIODevice::ReadOnly))
    {
        QString data = transform.readAll();
        transform.close();
        QJsonParseError jsonError;
        QJsonDocument transformer = QJsonDocument::fromJson(data.toUtf8(), &jsonError);
        if(jsonError.error == QJsonParseError::NoError)
        {
            root = transformer.object();
        }
        else
        {
            qDebug()<<jsonError.errorString();
        }
    }
}
示例#24
0
bool Profile::loadProfile(QString fileName, bool loadDefault) {

  QFile file(fileName);

  // Check if file exists, if not create default profile
  if(!file.exists()) {

    if(loadDefault) {
      loadDefaultProfile();
      return true;
    }
    else
      return false;
  }

  // Read profile data from file

  dataPoints.clear();

  QJsonDocument json;

  if(file.open(QFile::ReadOnly)) {
    qDebug() << "Loading profile data from " << fileName;

    QJsonParseError error;

    json = QJsonDocument().fromJson(file.readAll(), &error);

    // Check if JSON was correctly parsed
    if (error.error != QJsonParseError::NoError) {

      qDebug() << error.errorString();
      return false;
    }

    // Read JSON values
    QJsonObject object     = json.object();
    QJsonArray profileData = object.value("profileData").toArray();

    profileName = object.value("profileName").toString();

    // Convert the JSON array to a Trade List
    for(int i = 0; i < profileData.size(); i++) {

      // Convert the JSON values
      QJsonObject dataPointObject = profileData[i].toObject();

      float time = dataPointObject.value("time").toDouble();
      float temp = dataPointObject.value("temp").toDouble();

      // Create a trade object from the converted values
      DataPoint dataPoint(time, temp);

      // Append the new trade object to the trade list
      dataPoints.append(dataPoint);
    }
  }

  return true;
}
示例#25
0
int main(int argc, char *argv[])
{
    QCoreApplication application(argc, argv);
    QNetworkAccessManager nam;

    for (int i=1; i<argc; i++) {
        if      (!strcmp(argv[i], "-help"      )) { help(); exit(EXIT_SUCCESS); }
        else if (!strcmp(argv[i], "-json"      )) json = true;
        else if (!strcmp(argv[i], "-permissive")) permissive = true;
        else                                      { url_provided = true; process(argv[i], QByteArray(), nam); }
    }

    if (!url_provided) {
        QFile file;
        file.open(stdin, QFile::ReadOnly);
        while (!file.atEnd()) {
            const QByteArray line = file.readLine().simplified();
            if (line.isEmpty())
                continue;

            QJsonParseError error;
            process(json ? QJsonDocument::fromJson(line, &error).object().value("URL").toString()
                         : QString::fromLatin1(line),
                    json ? line : QByteArray(),
                    nam);

            if (json && (error.error != QJsonParseError::NoError))
                qDebug() << error.errorString();
        }
    }

    return EXIT_SUCCESS;
}
示例#26
0
Connection* ConfigHelper::configJsonToConnection(const QString &file)
{
    QFile JSONFile(file);
    JSONFile.open(QIODevice::ReadOnly | QIODevice::Text);
    if (!JSONFile.isOpen()) {
        qCritical() << "Error: cannot open " << file;
    }
    if(!JSONFile.isReadable()) {
        qCritical() << "Error: cannot read " << file;
    }

    QJsonParseError pe;
    QJsonDocument JSONDoc = QJsonDocument::fromJson(JSONFile.readAll(), &pe);
    JSONFile.close();
    if (pe.error != QJsonParseError::NoError) {
        qCritical() << pe.errorString();
    }
    if (JSONDoc.isEmpty()) {
        qCritical() << "JSON Document" << file << "is empty!";
        return nullptr;
    }
    QJsonObject configObj = JSONDoc.object();
    SQProfile p;
    p.serverAddress = configObj["server"].toString();
    p.serverPort = configObj["server_port"].toInt();
    p.localAddress = configObj["local_address"].toString();
    p.localPort = configObj["local_port"].toInt();
    p.method = configObj["method"].toString();
    p.password = configObj["password"].toString();
    p.timeout = configObj["timeout"].toInt();
    Connection *con = new Connection(p, this);
    return con;
}
QVariant ContentItemInterfacePrivate::parseReplyDataVariant(const QByteArray &replyData, bool *ok)
{
    QVariant parsed;

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    QJson::Parser jsonParser;
    parsed = jsonParser.parse(replyData, ok);
    if (!*ok) {
        qWarning() << Q_FUNC_INFO << "Error parsing JSON file:" << jsonParser.errorString()
                   << "at" << jsonParser.errorLine();
    }
#else
    QJsonParseError jsonError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(replyData, &jsonError);
    *ok = !jsonDocument.isEmpty();
    if (!*ok) {
        qWarning() << Q_FUNC_INFO << "Error parsing JSON file:" << jsonError.errorString()
                   << "at" << jsonError.offset;
    }
    parsed = jsonDocument.toVariant();
#endif

    if (!*ok) {
        parsed.clear();
    }

    return parsed;
}
示例#28
0
qint32 RtCmdClient::requestBufsize()
{
    //Send
    m_commandManager["getbufsize"].send();

    //Receive
    m_qMutex.lock();
    QByteArray t_sJsonCommands = m_sAvailableData.toUtf8();
    m_qMutex.unlock();

    //Parse
    QJsonParseError error;
    QJsonDocument t_jsonDocumentOrigin = QJsonDocument::fromJson(t_sJsonCommands, &error);

    if (error.error == QJsonParseError::NoError)
    {
        qDebug() << t_jsonDocumentOrigin;//"Received Commands" << m_commandManager.commandMap().keys();

        //Switch to command object
        if(t_jsonDocumentOrigin.isObject() && t_jsonDocumentOrigin.object().value(QString("bufsize")) != QJsonValue::Undefined)
        {
            qint32 size = (qint32)t_jsonDocumentOrigin.object().value(QString("bufsize")).toDouble();
            return size;
        }
    }

    qCritical() << "Unable to parse JSON response: " << error.errorString();
    return -1;
}
bool MentionsTimelineQueryHandler::treatReply(const QByteArray &data, std::vector<Tweet> &items,
                                              QString &errorMessage, Placement &placement)
{
    QJsonParseError error {-1, QJsonParseError::NoError};
    QJsonDocument document {QJsonDocument::fromJson(data, &error)};
    if (error.error != QJsonParseError::NoError) {
        errorMessage = error.errorString();
        placement = Discard;
        return false;
    }

    const QJsonArray tweets (document.array());
    items.reserve(tweets.size());
    for (const QJsonValue &tweet : tweets) {
        if (tweet.isObject()) {
            items.emplace_back(tweet.toObject());
        }
    }

    if (!items.empty()) {
        m_sinceId = std::begin(items)->id();
    }

    placement = Prepend;
    return true;
}
示例#30
0
void ShellUI::reloadConfig()
{
    m_properties.clear();
    qDeleteAll(m_bindings);
    m_bindings.clear();

    QJsonObject object;
    if (m_config.contains(QStringLiteral("Shell"))) {
        object = m_config[QStringLiteral("Shell")].toObject();
    } else {
        QJsonParseError err;
        QJsonDocument doc = QJsonDocument::fromJson(defaultShell, &err);
        if (err.error != QJsonParseError::NoError) {
            qDebug() << "Cannot parse the default shell config" << err.errorString();
        }
        object = doc.object();
        m_config[QStringLiteral("Shell")] = object;
    }
    QJsonObject properties = object[QStringLiteral("properties")].toObject();
    for (auto i = properties.constBegin(); i != properties.constEnd(); ++i) {
        setProperty(qPrintable(i.key()), i.value().toVariant());
        m_properties << i.key();
    }

    QJsonArray bindings = object[QStringLiteral("bindings")].toArray();
    for (auto i = bindings.begin(); i != bindings.end(); ++i) {
        const QJsonObject &binding = (*i).toObject();
        if (!parseBinding(binding)) {
            qDebug() << "Cannot parse binding" << binding;
        }
    }

    foreach (UiScreen *screen, m_screens) {
        loadScreen(screen);
    }