示例#1
0
QJsonDocument
CRestWorker::get_request_json_document(const QString &link,
                                       int &http_code,
                                       int &err_code,
                                       int &network_error) {
  QUrl url_env(CSettingsManager::Instance().get_url().arg(link));
  QNetworkRequest req(url_env);
  req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
  QByteArray arr = send_get_request(req, http_code, err_code, network_error);
  QJsonDocument doc  = QJsonDocument::fromJson(arr);
  if (doc.isNull()) {
    err_code = RE_NOT_JSON_DOC;
    CApplicationLog::Instance()->LogInfo("Received not json document from url : %s", link.toStdString().c_str());
    return QJsonDocument();
  }
  return doc;
}
示例#2
0
void TextTranslateNet::httpfinished(QNetworkReply* reply){
    qDebug()<<"end translate!!!!!";
    //qDebug()<<reply->errorString()<<QString::fromUtf8(reply->readAll());
    QJsonDocument jsonDoc;
    QJsonObject jsonObj;
    QString resutstr="";
    jsonDoc=QJsonDocument::fromJson(reply->readAll());
    if(!jsonDoc.isNull()){
        jsonObj=jsonDoc.object();
        if(jsonObj.contains("error_msg")){
            resutstr=QString(tr("服务器返回错误:%1")).arg(jsonObj.value("error_msg").toString());
        }else{
            resutstr=jsonObj.value("trans_result").toArray()[0].toObject().value("dst").toString();
        }
    }
    emit translateFinshed(resutstr);
}
示例#3
0
void CatalogContent::read(std::string filePath)
{
    using namespace sb::utility::file;
    if(!fileExists(filePath))
        THROW_RUNTIME_ERROR("Cannot open catalog content at '" + filePath + "'. File does not exist.");


    QFile file(QString::fromStdString(filePath));
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QString content = file.readAll();
    file.close();
    QJsonDocument catalogContent = QJsonDocument::fromJson(content.toUtf8());

    if(catalogContent.isNull())
        THROW_RUNTIME_ERROR("Failed to read catalog content at '" + filePath + "'.");

    QJsonArray array = catalogContent.array();
    std::string dir = getPath(filePath);
    for(const QJsonValue& val : array)
    {
        QJsonObject obj = val.toObject();
        QString type = obj["type"].toString();

        if(type == "appearances")
        {
            Appearances a;
            a.path = dir + "/" + obj["file"].toString().toStdString();
            mAppearances.push_back(a);
        }
        else if(type == "sprite")
        {
            SpriteSheet s;
            s.path = dir + "/" + obj["file"].toString().toStdString();
            s.spriteSize = (SpriteSize)obj["spritetype"].toInt();
            s.firstSpriteId = obj["firstspriteid"].toInt();
            s.lastSpriteId = obj["lastspriteid"].toInt();
            s.area = obj["area"].toInt();
            mSpriteSheets.push_back(s);
        }
        else
        {
            THROW_RUNTIME_ERROR("Error reading catalog content. Unimplemented type.");
        }
    }
}
示例#4
0
// Non-200 responses are not json:
QJsonObject QmlMarketplace::failResponse(const QString& label, QNetworkReply* reply) {
    QString response = reply->readAll();
    qWarning(commerce) << "FAILED" << label << response;

    // tempResult will be NULL if the response isn't valid JSON.
    QJsonDocument tempResult = QJsonDocument::fromJson(response.toLocal8Bit());
    if (tempResult.isNull()) {
        QJsonObject result
        {
            { "status", "fail" },
            { "message", response }
        };
        return result;
    }
    else {
        return tempResult.object();
    }
}
示例#5
0
bool Messages::parseJsonUsers(ArmaMessage &message, QList<peer>& usersList) {
	usersList.clear();
	QJsonDocument jsonDoc = QJsonDocument::fromJson(message);
	if (jsonDoc.isNull()) {
		return false;
	}
	QJsonObject jsonObject = jsonDoc.object();
	if (jsonObject["users"].isArray()) {
		QJsonArray users = jsonObject["users"].toArray();
		foreach (QJsonValue user, users)
		{
			QJsonObject userObject = user.toObject();
			peer p;
			p.address = userObject["address"].toString();
			p.name = userObject["nick"].toString();
			p.listeningPort = userObject["port"].toInt();
			usersList.append(p);
		}
示例#6
0
QJsonObject Api::parseJson(QByteArray response)
{
    QJsonDocument jsonDocument = QJsonDocument::fromJson(response);
    QJsonObject jsonObject;
    jsonObject.insert("length", response.length());
    if (jsonDocument.isEmpty() || jsonDocument.isNull()) {
        jsonObject.insert("data", QJsonObject());
    } else {
        QJsonValue value;
        if (jsonDocument.isObject()) {
            value = QJsonValue(jsonDocument.object());
        } else {
            value = QJsonValue(jsonDocument.array());
        }
        jsonObject.insert("content", value);
    }
    return jsonObject;
}
void AddressBookModel::walletInitCompleted(int _error, const QString& _error_text) {
  if (!_error) {
    QFile addressBookFile(Settings::instance().getAddressBookFile());
    if (addressBookFile.open(QIODevice::ReadOnly)) {
      QByteArray file_content = addressBookFile.readAll();
      QJsonDocument doc = QJsonDocument::fromJson(file_content);
      if (!doc.isNull()) {
        m_addressBook = doc.array();
      }

      addressBookFile.close();
      if (!m_addressBook.isEmpty()) {
        beginInsertRows(QModelIndex(), 0, m_addressBook.size() - 1);
        endInsertRows();
      }
    }
  }
}
示例#8
0
VersionFilePtr VersionBuilder::parseBinaryJsonFile(const QFileInfo &fileInfo)
{
	QFile file(fileInfo.absoluteFilePath());
	if (!file.open(QFile::ReadOnly))
	{
		throw JSONValidationError(QObject::tr("Unable to open the version file %1: %2.")
									  .arg(fileInfo.fileName(), file.errorString()));
	}
	QJsonDocument doc = QJsonDocument::fromBinaryData(file.readAll());
	file.close();
	if (doc.isNull())
	{
		file.remove();
		throw JSONValidationError(
			QObject::tr("Unable to process the version file %1.").arg(fileInfo.fileName()));
	}
	return VersionFile::fromJson(doc, file.fileName(), false, false);
}
示例#9
0
void SearchJob::requestFinished()
{
    const QByteArray data = d->m_reply->readAll();
    //qDebug() << data;
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        d->m_errorMessage = QStringLiteral("Invalid json received");
    }
    QJsonObject root = doc.object();
    QJsonArray results = root.value(QStringLiteral("results")).toArray();
    d->m_result.load(results, d->m_params.configuration);

    d->m_reply->deleteLater();
    d->m_reply = 0;

    emit result(this);
    deleteLater();
}
示例#10
0
void DataStore::loadBattles(const QString& file_name)
{
  QFile battles_file(file_name);
  if (!battles_file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    qDebug() << "Failed to open data file: " << file_name;
    return;
  }

  const QString battles_content = battles_file.readAll();
  const QJsonDocument battles_doc = QJsonDocument::fromJson(battles_content.toUtf8());

  if (battles_doc.isNull() || !battles_doc.isArray()) {
    qDebug() << "Invalid JSON in file " << file_name;
    return;
  }

  battles_ = JsonDataStore<Battle>::loadArray(battles_doc.array(), "name");
}
QList<QSharedPointer<UpworkCategory>> UpworkCategoryReader::readCategories(QNetworkReply * reply) const
{
    QList<QSharedPointer<UpworkCategory>> categories;
    QJsonDocument document = QJsonDocument::fromJson(reply->readAll());
    if (!document.isNull() && document.isObject())
    {
        QJsonValue categoriesValue = document.object()["categories"];
        if (categoriesValue.isArray())
        {
            foreach (const QJsonValue & categoryValue, categoriesValue.toArray())
            {
                UpworkCategory * category = getCategory(categoryValue);
                if (checkIsValidCategory(category))
                {
                    categories.append(QSharedPointer<UpworkCategory>(category));
                }
            }
        }
JsonSummaryReader::JsonSummaryReader(QString file_path)
{
    QFile *file = new QFile(file_path);
    if (!file->open(QIODevice::ReadOnly))
        throw std::runtime_error("Unable to open JSON summary file " + file_path.toStdString());
    QByteArray data = file->readAll();
    QJsonDocument json = QJsonDocument::fromJson(data);
    if (json.isNull())
        throw std::runtime_error("Unable to parse the JSON summary file " + file_path.toStdString());
    if (!json.isObject())
        throw std::runtime_error("The json summary must be a valid json object " + file_path.toStdString());

    QJsonObject json_summary = QJsonObject(json.object());
    readGlobal(json_summary["Field"].toObject());
    readFieldProps(json_summary["Field"].toObject()["Properties"].toObject());
    readWellProps(json_summary["Wells"].toArray());
    file->close();

}
示例#13
0
QByteArray
toJson( const QVariant &variant, bool* ok )
{
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
    QJsonDocument doc = QJsonDocument::fromVariant( variant );
    if ( ok != NULL )
    {
        *ok = !doc.isNull();
    }
    return doc.toJson( QJsonDocument::Compact );
#else
    QJson::Serializer serializer;
    QByteArray ret = serializer.serialize( variant );
    if ( ok != NULL )
    {
        *ok = !ret.isNull();
    }
    return ret;
#endif
}
示例#14
0
//------------------------------------------------------------------------------
// Name: operator==
//------------------------------------------------------------------------------
bool QJsonDocument::operator==(const QJsonDocument &other) const {

	if(isArray() && other.isArray()) {
		return array() == other.array();
	}

	if(isObject() && other.isObject()) {
		return object() == other.object();
	}

	if(isEmpty() && other.isEmpty()) {
		return true;
	}

	if(isNull() && other.isNull()) {
		return true;
	}

	return false;
}
示例#15
0
static bool readGpuFeatures(const QOpenGLConfig::Gpu &gpu,
                            const QString &osName,
                            const QVersionNumber &kernelVersion,
                            const QByteArray &jsonAsciiData,
                            QSet<QString> *result, QString *errorMessage)
{
    result->clear();
    errorMessage->clear();
    QJsonParseError error;
    const QJsonDocument document = QJsonDocument::fromJson(jsonAsciiData, &error);
    if (document.isNull()) {
        const int lineNumber = 1 + jsonAsciiData.left(error.offset).count('\n');
        QTextStream str(errorMessage);
        str << "Failed to parse data: \"" << error.errorString()
            << "\" at line " << lineNumber << " (offset: "
            << error.offset << ").";
        return false;
    }
    return readGpuFeatures(gpu, osName, kernelVersion, document, result, errorMessage);
}
void MainWindow::on_actionOpen_Preset_triggered()
{
    QFileDialog dialog(this);
    dialog.setViewMode(QFileDialog::Detail);
    dialog.setAcceptMode(QFileDialog::AcceptOpen);
    dialog.setFileMode(QFileDialog::AnyFile);
    QStringList filters;
    filters << NAME_FILTER_PRESET
            << NAME_FILTER_ANY;
    dialog.setNameFilters(filters);
    QString file;
    if (dialog.exec())
    {
        QFile file(dialog.selectedFiles().at(0));
        if (file.exists())
        {
            file.open(QIODevice::ReadOnly | QIODevice::Text);
            QString jsonString = (QString) file.readAll();
            QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
            if (doc.isNull())
            {
                QMessageBox box;
                QString boxText;
                boxText.append("It appears that ")
                       .append(QFileInfo(file).fileName())
                       .append("is not a valid preset file");
                box.setText("It appears that file is not a valid preset");
                box.setStandardButtons(QMessageBox::Ok);
                box.exec();
            }
            else
            {
                QJsonObject json = doc.object();
                taskTab->setValuesFromJson(json);
                audioTab->setValuesFromJson(json);
                visualTab->setValuesFromJson(json);
            }
        }

    }
}
示例#17
0
void ChatServer::receiveData() {
    QTcpSocket * socket = qobject_cast<QTcpSocket*>(sender());
    QByteArray received = socket->readAll();

    // в received может содержаться несколько сообщений
    // их надо разбить:
    while (received.length()) {
        // сообщение возьмет себе столько, сколько нужно
        QJsonDocument doc = QJsonDocument::fromBinaryData(received);
        if (doc.isNull()) {
            // плохие данные
            emit alert("Unknown message format");
            return;
        }

        QVariantMap data = doc.object().toVariantMap();
        if (!data.contains("type")) {
            emit alert("Message should have 'type' key");
            return;
        }

        // конвертация типа в const char* для рассчета CRC
        auto typeString = data["type"].toString();
        auto typeBuffer = typeString.toUtf8();
        auto typeChars = typeBuffer.constData();

        qWarning() << "get message:" << doc;

        switch (mt(typeChars)) {
            case mt("login"): processLoggingInData(socket, data); break;
            case mt("signin"): processSigningInData(socket, data); break;
            case mt("logout"): processLoggingOutData(socket, data); break;
            case mt("changestatus"): processChangingStatusData(socket, data); break;
            case mt("sendmessage"): processSendingData(socket, data); break;
            case mt("messagereceived"): processMessageReceivedData(socket, data); break;
            default: alert("Unknown message type"); break;
        }
        // сдвиг полученного массива на кол-во считанных данных
        received = received.right(received.length() - doc.toBinaryData().length());
    }
}
示例#18
0
bool Parser::ParseCart(const QString &str, Cart &cart,
        const QHash<QString, Goods *> &pGoodsMap) {
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
    if (doc.isNull()) {
        return false;
    }

    // json array containing all items
    QJsonArray jCodeArray = doc.array();
    if (jCodeArray.isEmpty()) { // no items or error json data
        return false;
    }

    // parse each item
    for (int i = 0; i < jCodeArray.size(); ++i) {
        QJsonValue jValue = jCodeArray.at(i);
        if (jValue.isString()) {
            QString strItem = jValue.toString();

            QString strCode;
            int nCnt = 0;
            // parse barcode and count
            int pos = strItem.indexOf("-");
            if (-1 == pos) {
                strCode = strItem;
                nCnt = 1;
            } else {
                strCode = strItem.left(pos);
                nCnt = strItem.mid(pos + 1).toInt();
                nCnt = (nCnt > 0) ? nCnt : 1;
            }

            // add item
            cart.Insert(pGoodsMap.value(strCode), nCnt);
        }
    }

    return true;
}
void LinAuthentication::on_sigTokenRequestFinished(QNetworkReply* networkReply)
{
    if (QNetworkReply::NetworkError::NoError == networkReply->error())
    {
        QString strJson(networkReply->readAll());
        Q_ASSERT(!strJson.isEmpty());

        QJsonDocument jsonDoc = QJsonDocument::fromJson(strJson.toUtf8());
        Q_ASSERT(!jsonDoc.isNull());

        QJsonObject jsonObj = jsonDoc.object();
        double expiresIn = jsonObj[LinAuthParameters::kLinJsonExpiresIn].toDouble();
        QString accessToken = jsonObj[LinAuthParameters::kLinJsonAccessToken].toString();

        Q_ASSERT(expiresIn > 0);
        Q_ASSERT(!accessToken.isEmpty());

        emit sigAuthTokenDelivered(accessToken, expiresIn);
    }
    else
        emit sigAuthError(QString::number(networkReply->error()), "");
}
示例#20
0
QVariantList CBAttachmentsProvider::attributesForId(const QString &recId)
{
    if (QDir(pathForId(recId)).exists()){
        QString filename=attributePath(recId);
         QFile file(filename);
         if (!file.open(QIODevice::ReadOnly)){
             qWarning("Cannot open attribute json");
         }
         QString jsonData = file.readAll();
         file.close();

         QJsonDocument sd = QJsonDocument::fromJson(jsonData.toUtf8());

         if (sd.isNull()){
            qWarning("Wrong file attribute json format");
         }
         return sd.array().toVariantList();
    }
    else{
        return QVariantList();
    }
}
示例#21
0
void ModuleObject::load(QV4::ExecutionEngine *v4, Heap::ModuleObject *moduleObject, const QString &path)
{
    QV4::Scope scope(v4);
    QV4::Scoped<ModuleObject> self(scope, moduleObject);

    const QFileInfo fi(path);
    self->d()->filename = path;
    self->d()->dirname = fi.absolutePath();

    const QString suffix = fi.suffix();
    if (suffix == QStringLiteral("js")) {
        compile(v4, self->d());
    } else if (suffix == QStringLiteral("json")) {
        QScopedPointer<QFile> file(new QFile(self->d()->filename));
        if (!file->open(QIODevice::ReadOnly)) {
            v4->throwError(QString("require: Cannot open file '%1'").arg(file->fileName()));
            return;
        }
        QJsonDocument json = QJsonDocument::fromJson(file->readAll());
        if (json.isNull()) {
            v4->throwSyntaxError(QStringLiteral("Unexpected end of input"));
            return;
        }

        QV4::ScopedObject o(scope);
        if (json.isObject())
            o = QV4::JsonObject::fromJsonObject(v4, json.object());
        else if (json.isArray())
            o = QV4::JsonObject::fromJsonArray(v4, json.array());
        self->d()->exports = o->d();

    } else {
        qFatal("Wrong file type"); /// TODO: Remove
        return;
    }

    self->d()->loaded = true;
}
QVariantList LocalJsonServer::readFromSocket(QLocalSocket* socket)
{
  QVariantList lst;

  while (socket->canReadLine())
  {
    QByteArray data = socket->readLine();
    if (!data.isNull())
    {
      QJsonParseError err;
      QJsonDocument doc = QJsonDocument::fromJson(data, &err);
      if (doc.isNull())
      {
        QLOG_WARN() << "Failed to parse message from client:" << err.errorString();
        continue;
      }

      lst << doc.toVariant();
    }
  }

  return lst;
}
示例#23
0
文件: job.cpp 项目: KDE/libkgapi
QString Job::Private::parseErrorMessage(const QByteArray &json)
{
    QJsonDocument document = QJsonDocument::fromJson(json);
    if (!document.isNull()) {
        QVariantMap map = document.toVariant().toMap();
        QString message;

        if (map.contains(QStringLiteral("error"))) {
            map = map.value(QStringLiteral("error")).toMap();
        }

        if (map.contains(QStringLiteral("message"))) {
            message.append(map.value(QStringLiteral("message")).toString());
        } else {
            message = QLatin1String(json);
        }

        return message;

    } else {
        return QLatin1String(json);
    }
}
QString setjson(QString filename, bool indentify) {
    QFile f(filename);
    if (!f.exists()) {
        return "ERROR: File does not exist.";
    }
    QJsonParseError jError;
    f.open(QIODevice::ReadOnly);
    QJsonDocument j = QJsonDocument::fromJson(f.readAll(), &jError);
    f.close();
    if (j.isNull()) {
        f.close();
        return "ERROR: "+jError.errorString();
    }
    f.open(QIODevice::WriteOnly|QIODevice::Truncate);
    if (indentify) {
        f.write(j.toJson(QJsonDocument::Indented));
        f.close();
        return "JSON rewritten as: Indented.";
    }
    f.write(j.toJson(QJsonDocument::Compact));
    f.close();
    return "JSON rewritten as: Compact.";
}
示例#25
0
QJsonObject AndroidStyle::loadStyleData()
{
    QString stylePath(QLatin1String(qgetenv("MINISTRO_ANDROID_STYLE_PATH")));
    const QLatin1Char slashChar('/');
    if (!stylePath.isEmpty() && !stylePath.endsWith(slashChar))
        stylePath += slashChar;

    QString androidTheme = QLatin1String(qgetenv("QT_ANDROID_THEME"));
    if (!androidTheme.isEmpty() && !androidTheme.endsWith(slashChar))
        androidTheme += slashChar;

    if (stylePath.isEmpty()) {
        stylePath = QLatin1String("/data/data/org.kde.necessitas.ministro/files/dl/style/")
                  + QLatin1String(qgetenv("QT_ANDROID_THEME_DISPLAY_DPI")) + slashChar;
    }
    Q_ASSERT(!stylePath.isEmpty());

    if (!androidTheme.isEmpty() && QFileInfo(stylePath + androidTheme + QLatin1String("style.json")).exists())
        stylePath += androidTheme;

    QFile f(stylePath + QLatin1String("style.json"));
    if (!f.open(QIODevice::ReadOnly))
        return QJsonObject();

    QJsonParseError error;
    QJsonDocument document = QJsonDocument::fromJson(f.readAll(), &error);
    if (document.isNull()) {
        qCritical() << error.errorString();
        return QJsonObject();
    }

    if (!document.isObject()) {
        qCritical() << "Style.json does not contain a valid style.";
        return QJsonObject();
    }
    return document.object();
}
示例#26
0
void SQLExample::readConfig() {
    QFile jsonFile("config.json");

    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        ui->statusLabel->setText("Unable to open config file!");
        return;
    }

    QByteArray jsonData = jsonFile.readAll();
    jsonFile.close();
    QJsonParseError* err = new QJsonParseError();
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, err);

    if (err->error != 0) {
        qDebug() << err->errorString();
    }

    if (doc.isNull()) {
        ui->statusLabel->setText("Invalid config file format!");
        return;
    }
    else if (doc.isObject()) {
        QJsonObject jObject = doc.object();
        QVariantMap config = jObject.toVariantMap();
        dbmstype = config["dbmstype"].toString();
        hostname = config["hostname"].toString();
        database = config["database"].toString();
        username = config["username"].toString();
        password = config["password"].toString();
        listQuery = config["list_query"].toString();
        infoQuery = config["info_query"].toString();
        headers = config["info_headers"].toStringList();
        playlistQuery = config["playlist_query"].toString();
        statusQuery = config["status_query"].toString();
        eventQuery = config["event_query"].toString();
    }
}
示例#27
0
void TwitterSearch::searchResultsReturned(KJob *job)
{
    qCDebug(CHOQOK);
    if (!job) {
        qCDebug(CHOQOK) << "job is a null pointer";
        Q_EMIT error(i18n("Unable to fetch search results."));
        return;
    }

    const SearchInfo info = mSearchJobs.take(job);
    QList<Choqok::Post *> postsList;
    if (job->error()) {
        qCCritical(CHOQOK) << "Error:" << job->errorString();
        Q_EMIT error(i18n("Unable to fetch search results: %1", job->errorString()));
    } else {
        KIO::StoredTransferJob *jj = qobject_cast<KIO::StoredTransferJob *>(job);
        const QJsonDocument json = QJsonDocument::fromJson(jj->data());

        if (!json.isNull()) {
            if (info.option == TwitterSearch::FromUser) {
                for (const QVariant elem: json.toVariant().toList()) {
                    postsList.prepend(readStatusesFromJsonMap(elem.toMap()));
                }
            } else {
                const QVariantMap map = json.toVariant().toMap();

                if (map.contains(QLatin1String("statuses"))) {
                    for (const QVariant elem: map[QLatin1String("statuses")].toList()) {
                        postsList.prepend(readStatusesFromJsonMap(elem.toMap()));
                    }
                }
            }
        }
    }

    Q_EMIT searchResultsReceived(info, postsList);
}
示例#28
0
bool
CloudDBChartClient::unmarshallAPIv1(QByteArray json, QList<ChartAPIv1> *charts) {

    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(json, &parseError);

    // all these things should not happen and we have not valid object to return
    if (parseError.error != QJsonParseError::NoError || document.isEmpty() || document.isNull()) {
        return false;
    }

    // do we have a single object or an array ?
    if (document.isObject()) {
        ChartAPIv1 chart;
        QJsonObject object = document.object();
        unmarshallAPIv1Object(&object, &chart);
        QJsonObject header = object["header"].toObject();
        CloudDBCommon::unmarshallAPIHeaderV1Object(&header, &chart.Header);
        charts->append(chart);

    } else if (document.isArray()) {
        QJsonArray array(document.array());
        for (int i = 0; i< array.size(); i++) {
            QJsonValue value = array.at(i);
            if (value.isObject()) {
                ChartAPIv1 chart;
                QJsonObject object = value.toObject();
                unmarshallAPIv1Object(&object, &chart);
                QJsonObject header = object["header"].toObject();
                CloudDBCommon::unmarshallAPIHeaderV1Object(&header, &chart.Header);
                charts->append(chart);
            }
        }
    }

    return true;
}
示例#29
0
int TestMonitor::loadJsonObject(QString &fileName,QJsonObject &jsonObj )
{
    pthread_mutex_lock(&conn_mutex);
    QFile file;

    QString sampleDir = "../../doc/json_sample/";
    sampleDir = "d:\\phonelin\\doc\\json_sample\\";
#if __linux__
    sampleDir = "/home/hamigua/phonelin/doc/json_sample/";
#endif

    file.setFileName(sampleDir + fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        DEBUG_INFO << "Failed to open json sameple file:" + sampleDir + fileName;
        pthread_mutex_unlock(&conn_mutex);
        return PL_RET_FAIL;
    }

    QString data = file.readAll();
    file.close();

    QJsonDocument sd = QJsonDocument::fromJson(data.toUtf8());
    if (!sd.isObject() || sd.isNull() || sd.isEmpty())
    {
        DEBUG_INFO << "Failed to open json sameple file:" + fileName;
        pthread_mutex_unlock(&conn_mutex);
        return PL_RET_FAIL;
    }

    jsonObj = sd.object();

    pthread_mutex_unlock(&conn_mutex);

    return PL_RET_OK;

}
示例#30
0
void RemoteModel::parseDirectoryListing(const QString& json, const QVariant& userdata)
{
    // Load new JSON root document assuming it's an array
    QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
    if(doc.isNull() || !doc.isArray())
        return;
    QJsonArray array = doc.array();

    // Get model index to store the new data under
    QModelIndex parent = userdata.toModelIndex();
    RemoteModelItem* parentItem = const_cast<RemoteModelItem*>(modelIndexToItem(parent));

    // An invalid model index indicates that this is a new root item. This means the old one needs to be entirely deleted first.
    if(!parent.isValid())
    {
        // Clear root item
        beginResetModel();
        delete rootItem;
        rootItem = new RemoteModelItem();
        endResetModel();

        // Set parent model index and parent item to the new values
        parent = QModelIndex();
        parentItem = rootItem;
    }

    // Insert data
    beginInsertRows(parent, 0, array.size());
    QList<RemoteModelItem*> items = RemoteModelItem::loadArray(QJsonValue(array), parentItem);
    foreach(RemoteModelItem* item, items)
        parentItem->appendChild(item);
    endInsertRows();

    // Emit directory listing parsed signal
    emit directoryListingParsed(parent);
}