예제 #1
0
파일: Mod.cpp 프로젝트: ACGaming/MultiMC5
// OLD format:
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc
void Mod::ReadMCModInfo(QByteArray contents)
{
	auto getInfoFromArray = [&](QJsonArray arr)->void
	{
		if (!arr.at(0).isObject())
			return;
		auto firstObj = arr.at(0).toObject();
		m_mod_id = firstObj.value("modid").toString();
		m_name = firstObj.value("name").toString();
		m_version = firstObj.value("version").toString();
		m_homeurl = firstObj.value("url").toString();
		m_description = firstObj.value("description").toString();
		QJsonArray authors = firstObj.value("authors").toArray();
		if (authors.size() == 0)
			m_authors = "";
		else if (authors.size() >= 1)
		{
			m_authors = authors.at(0).toString();
			for (int i = 1; i < authors.size(); i++)
			{
				m_authors += ", " + authors.at(i).toString();
			}
		}
		m_credits = firstObj.value("credits").toString();
		return;
	};
	QJsonParseError jsonError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
	// this is the very old format that had just the array
	if (jsonDoc.isArray())
	{
		getInfoFromArray(jsonDoc.array());
	}
	else if (jsonDoc.isObject())
	{
		auto val = jsonDoc.object().value("modinfoversion");
		int version = val.toDouble();
		if (version != 2)
		{
			QLOG_ERROR() << "BAD stuff happened to mod json:";
			QLOG_ERROR() << contents;
			return;
		}
		auto arrVal = jsonDoc.object().value("modlist");
		if (arrVal.isArray())
		{
			getInfoFromArray(arrVal.toArray());
		}
	}
}
예제 #2
0
const QJsonArray WorldInfo::load(QString filename) {
  QFile file(filename);
  if (!file.open(QIODevice::ReadOnly))
    throw InitException(tr("%1 is missing!").arg(filename));
  QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  file.close();

  if (doc.isNull())
    throw InitException(tr("%1 is corrupt").arg(filename));

  if (!doc.isArray())
    throw InitException(tr("%1 isn't an array").arg(filename));

  return doc.array();
}
bool IqWampJsonWebSocketHelper::parseMessage(const QString &message,
                                             QJsonArray *jsonMessage,
                                             IqWamp::MessageTypes *messageType)
{
    Q_CHECK_PTR(jsonMessage);
    Q_CHECK_PTR(messageType);

#ifdef IQWAMP_DEBUG_MODE
    qDebug() << "Reserve message" << message;
#endif

    QJsonParseError error;
    QJsonDocument messageDoc = QJsonDocument::fromJson(message.toLocal8Bit(), &error);

    if (error.error) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Error: " << error.errorString();
#endif
        return false;
    }

    if (!messageDoc.isArray()) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Message must be JSON array.";
#endif
        return false;
    }

    *jsonMessage = messageDoc.array();
    if (jsonMessage->size() < 2) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Message must be JSON array with size >= 2.";
#endif
        return false;
    }

    QJsonValue messageFirstParam = jsonMessage->first();
    if (!messageFirstParam.isDouble()) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Message must be JSON array with first int value.";
#endif
        return false;
    }

    *messageType = static_cast<IqWamp::MessageTypes>(messageFirstParam.toInt());

    return true;
}
예제 #4
0
void CryptocoinChartsMDP::getCurrenciesList(QList<Currency>& list) {
    QJsonDocument doc = sendRequest("http://www.cryptocoincharts.info/v2/api/listCoins");
    QJsonArray array = doc.array();
    //qDebug() << "-- json: " << doc;
    for(QJsonArray::const_iterator i=array.constBegin(); i != array.constEnd(); ++i) {
        const QJsonValue &val = *i;
        QJsonObject obj = val.toObject();
        //qDebug() << ":::: volume:::" << obj["volume_btc"];
        double volume = obj["volume_btc"].toString().toDouble();
        if(volume > 1.0) { // let's filter out low volume alt coins
          Currency c; c.code = obj["id"].toString().toUpper(); c.name = obj["name"].toString();
          list.append(c);
          //qDebug() << "-- value: " << c << list.length();
        }
    }
}
void
ThirdPartyLicenseSchemaManager::load_json_document(const QJsonDocument & json_document)
{
  // qInfo() << "Load Third Party Licenses JSON";

  QJsonArray array = json_document.array();

  for (const auto & json_value : array) {
    ThirdPartyLicensePtr third_party_license(json_value.toObject());
    // Fixme: keep one
    m_third_party_license_cache.add(third_party_license);
    m_third_party_licenses << third_party_license;
  }

  emit third_party_license_list_changed();
}
QList<DeviceInfo> deviceListFromJson(QString json)
{
    QList<DeviceInfo> list;
    QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
    for (auto jsonObj : doc.array()) {
        DeviceInfo device;
        auto obj = jsonObj.toObject();
        device.path = obj.value("path").toString();
        device.label = obj.value("label").toString();
        device.used = static_cast<quint32>(obj.value("used").toInt());
        device.total = static_cast<quint32>(obj.value("total").toInt());
        device.needFormat = obj.value("needformat").toBool();
        list.push_back(device);
    }
    return list;
}
예제 #7
0
bool XSAppBuilder::compileObject(const QFileInfo &source)
{
    if(source.suffix() == "xml")
    {
        qDebug()<<"xml";
        QFile file(source.filePath());
        QXmlInputSource inputSource(&file);
        QXmlSimpleReader reader;
        reader.setContentHandler(this);
        reader.setErrorHandler(this);
        return reader.parse(inputSource);
    }
    else if(source.suffix() == "json")
    {
        QFile file(source.filePath());
        if(!file.open(QIODevice::ReadOnly))
        {
            return false;
        }
        QString data = file.readAll();
        file.close();
        QJsonParseError jsonError;
        QJsonDocument jsonFile = QJsonDocument::fromJson(data.toUtf8(), &jsonError);
        if(jsonError.error == QJsonParseError::NoError)
        {
            if(jsonFile.isArray())
            {
                QJsonArray jsonArray = jsonFile.array();
                qDebug()<<"array: "<<jsonArray;
            }
            else if(jsonFile.isObject())
            {
                QJsonObject jsonObj = jsonFile.object();
                qDebug()<<"object: " << jsonObj;

            }
            return true;
        }
        else
        {
            qDebug()<<jsonError.errorString();
            return false;
        }
    }

    return false;
}
예제 #8
0
void MainWindow::finished()
{
    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(reply_->readAll(), &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        QList<QObject *> members;
        foreach (const QJsonValue& value, document.array()) {
            QJsonObject object = value.toObject();

            auto member = new Member(this);
            member->setName(object[TAG_NAME].toString());
            member->setAvatar(object[TAG_AVATAR].toString());
            members << member;
        }

        rootContext()->setContextProperty(TAG_MODEL, QVariant::fromValue(members));
    }
예제 #9
0
void RequestPlan::parseDates(QNetworkReply *reply)
{
    QString strReply= (QString)reply->readAll();
    if(strReply == "[]"){

        emit noPlansAvailable();

    }else{
        QJsonDocument doc = QJsonDocument::fromJson(strReply.toUtf8());
        QJsonArray allDates = doc.array();

        foreach (QJsonValue date, allDates) {
            QJsonObject dateObj = date.toObject();
            QVariantMap dateMap = dateObj.toVariantMap();
            emit datesReceived(dateMap);
        }
    }
예제 #10
0
//! Requests the properties for display to be fetched.
void ObjectVersionCore::requestPropertiesForDisplay()
{
	// Fetch information about the latest version.
	QString resource( "/objects/%1/%2/%3/properties?forDisplay=true" );
	QString args = resource.arg( m_objver.type() ).arg( m_objver.id() ).arg( m_objver.version() );
	QNetworkReply* reply = this->rest()->getJson( args );
	QObject::connect( reply, &QNetworkReply::finished,  [=]() {

		// Parse the returned JSON.
		QByteArray replyContent = reply->readAll();
		QJsonDocument result = QJsonDocument::fromJson( replyContent );
		QJsonArray propertiesForDisplay = result.array();

		// Store the properties for display.
		this->setPropertiesForDisplay( propertiesForDisplay );
	} );
}
예제 #11
0
void LoginManager::onAccessTokenRequestReady(QByteArray ba)
      {
      //qDebug() << "onAccessTokenRequestReady" << ba;
      if (_oauthManager->lastError() == KQOAuthManager::RequestUnauthorized) { // 401/406

            QJsonDocument jsonResponse = QJsonDocument::fromJson(ba);
            QJsonArray array = jsonResponse.array();
            QString message = tr("Unsuccessful login. Please try again.");
            if (array.size() > 0) {
                 QJsonObject o = array.at(0).toObject();
                 if (o.value("code") != QJsonValue::Undefined) {
                 	   QString code = o["code"].toString();
                     if (code == "USER_AUTHENTICATION_FAILED") {
                           message = tr("Sorry, wrong email address, username or password. Please check again. %1Have you forgotten your password%2?")
                                       .arg("<a href=\"https://musescore.com/user/password\">")
                                       .arg("</a>");
                           }
                     else if (code == "USER_DENIED") {
                           message = tr("This account has been blocked.");
                           }
                     else if (code == "USER_NOT_ACTIVATED") {
                           message = tr("Your account has not been activated yet. Please check your mailbox to activate your account or %1request a new activation email%2.")
                                       .arg("<a href=\"https://musescore.com/user/resendregistrationpassword\">")
                                       .arg("</a>");
                           }
                     else if (code == "USER_TIMESTAMP_EXPIRED") {
                           message = tr("The local time on your device is not set right. Please check it and adjust. It's advised to set the time/timezone to automatic. If you still can't log in, %1contact us%2.")
                                       .arg("<a href=\"https://musescore.com/contact?category=Login%20problems\">")
                                       .arg("</a>");
                           }
                     }
                 }
                 emit loginError(message);
            }
      else if (_oauthManager->lastError() == KQOAuthManager::NetworkError) {
            QMessageBox::critical(0, tr("Network error"), tr("Please check your Internet connection"));
            }
      else if (_oauthManager->lastError() == KQOAuthManager::ContentOperationNotPermittedError) {
            QMessageBox::critical(0, tr("Please upgrade"), tr("Your MuseScore version is too old to use this feature.\n"
                                                              "%1Please upgrade first%2.")
                                  .arg("<a href=\"https://musescore.org\">")
                                  .arg("</a>")
                                  .replace("\n", "<br/>"));
            }
      }
예제 #12
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.");
        }
    }
}
예제 #13
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;
}
예제 #14
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");
}
예제 #15
0
void DataManager::loadGit(const QJsonDocument &jd)
{
    QJsonArray ja = jd.array();
    for (int i=0; i<ja.count(); i++) {
        if(!ja[i].isObject())
            continue;
        Datum *d = new Datum(this);
        foreach(const QString &key, ja[i].toObject().keys())
            d->setProperty(key.toLatin1().constData(), ja[i].toObject().value(key).toString());
        if (d->sha1().isEmpty()) {
            delete d;
            continue;
        } else {
            m_dataMap[d->sha1()] = d;
        }
        m_data << d;
    }
}
예제 #16
0
파일: qjsonview.cpp 프로젝트: Iownnoname/qt
void QJsonView::setJson(const QString &text)
{
    clear();
    QJsonDocument document = QJsonDocument::fromJson(text.toUtf8());

    if(document.isArray())
    {
        buildArray("", document.array());
    }
    else if(document.isObject())
    {
        buildObject("", document.object());
    }
    else
    {
        throw -1;
    }
}
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();
      }
    }
  }
}
예제 #18
0
void LogFile::update()
{
    if (m_fileName.isEmpty()) return;

    //QLockFile lock(m_fileName);
    //lock.lock();

    m_items.clear();

    QFile f(m_fileName);
    if (f.open(QFile::ReadOnly))
    {
        QByteArray data = f.readAll();
        QString s = QString::fromUtf8(data);
        if (s.endsWith(",\n")) s = s.mid(0, s.length()-2);
        //s.replace("\n", "");
        //s = "{\"data\": [" + s + "]}";
        s = "[" + s + "]";

        QJsonParseError err;
        QJsonDocument doc = QJsonDocument::fromJson(s.toLatin1(), &err);
        if (err.error != QJsonParseError::NoError)
        {
            qWarning("Parse error: %s at %d", qPrintable(err.errorString()), err.offset);
            return;
        }

        QJsonArray a = doc.array();
        foreach (QJsonValue v, a)
        {
            QJsonObject o = v.toObject();
            LogRecord r;
            r.capacity = o["capacity"].toDouble();
            r.isCharging = o["isCharging"].toBool();
            QJsonArray proc = o["proc"].toArray();
            foreach (QJsonValue v2, proc)
            {
                QJsonArray a2 = v2.toArray();
                ProcessRecord pr;
                pr.name = a2[0].toString();
                pr.pid = a2[1].toInt();
                pr.time = a2[2].toInt();
                r.proc.append(pr);
            }
예제 #19
0
const QJsonObject NetworkManager::deviceConnInfo(const QUuid &uuid) const
{
    const QString addr = deviceHwAddr(uuid);
    if (addr.isEmpty())
        return QJsonObject();

    const QJsonDocument infos = QJsonDocument::fromJson(m_networkInter->GetActiveConnectionInfo().value().toUtf8());
    Q_ASSERT(infos.isArray());

    for (auto info : infos.array())
    {
        Q_ASSERT(info.isObject());
        const QJsonObject obj = info.toObject();
        if (obj.contains("HwAddress") && obj.value("HwAddress").toString() == addr)
            return obj;
    }

    return QJsonObject();
}
예제 #20
0
QMap<QString, Bookmark*> BookmarkManager::load() {
    QMap<QString, Bookmark*> bookmarks;
    QString settingsLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/bookmarks.json";
    QScopedPointer<QFile> file(new QFile(settingsLocation));

    if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Unable to open bookmarks " << settingsLocation;

        file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/content/bookmarks.json")));
        if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
            qWarning() << "Unable to open bookmarks defaults";
            return bookmarks;
        }
    }

    QJsonDocument doc = QJsonDocument::fromJson(file->readAll());
    if (doc.isArray()) {
        QJsonArray array = doc.array();
        QJsonArray::iterator i;
        QRegularExpression jollaUrl("^http[s]?://(together.)?jolla.com");
        for (i=array.begin(); i != array.end(); ++i) {
            if ((*i).isObject()) {
                QJsonObject obj = (*i).toObject();
                QString url = obj.value("url").toString();
                QString favicon = obj.value("favicon").toString();
                if (url.contains(jollaUrl) ||
                        url.startsWith("http://m.youtube.com/playlist?list=PLQgR2jhO_J0y8YSSvVd-Mg9LM88W0aIpD")) {
                    favicon = "image://theme/icon-m-service-jolla";
                }

                Bookmark* m = new Bookmark(obj.value("title").toString(),
                                           url,
                                           favicon,
                                           obj.value("hasTouchIcon").toBool());
                bookmarks.insert(url, m);
            }
        }
    } else {
        qWarning() << "Bookmarks.json should be an array of items";
    }
    file->close();
    return bookmarks;
}
예제 #21
0
void MarketData::parseCoinPairRates(QNetworkReply *reply)
{
    QString data = reply->readAll();
    QJsonParseError jsonParseError;
    QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8(), &jsonParseError);
    QJsonArray mainArray = jsonResponse.array();
    foreach (const QJsonValue &value, mainArray) {
        QJsonObject marketPair = value.toObject();
        if (marketPair.contains("Symbol") && marketPair["Symbol"].toString() == "LEO/GBP")
        {
            if (marketPair.contains("Rate"))
            {
                currentGBPPrice = marketPair["Rate"].toDouble();
                currentGBPBalancePrice = currentBalance * currentGBPPrice / 1000000;
            }
            this->ui->labelGBP1->setText(QSTRING_DOUBLE(currentGBPPrice));
            this->ui->labelGBP->setText(QSTRING_DOUBLE(currentGBPBalancePrice));
        }else if (marketPair.contains("Symbol") && marketPair["Symbol"].toString() == "LEO/EUR"){
            if (marketPair.contains("Rate"))
            {
                currentEURPrice = marketPair["Rate"].toDouble();
                currentEURBalancePrice = currentBalance * currentEURPrice / 1000000;
            }
            this->ui->labelEUR1->setText(QSTRING_DOUBLE(currentEURPrice));
            this->ui->labelEUR->setText(QSTRING_DOUBLE(currentEURBalancePrice));
        }else if (marketPair.contains("Symbol") && marketPair["Symbol"].toString() == "LEO/BTC"){
            if (marketPair.contains("Rate"))
            {
                currentBTCPrice = marketPair["Rate"].toDouble();
                currentBTCBalancePrice = currentBalance * currentBTCPrice / 1000000;
            }
            this->ui->labelBTC1->setText(QSTRING_DOUBLE(currentBTCPrice));
            this->ui->labelBTC->setText(QSTRING_DOUBLE(currentBTCBalancePrice));
        }else if (marketPair.contains("Symbol") && marketPair["Symbol"].toString() == "LEO/USD"){
            if (marketPair.contains("Rate"))
            {
                currentUSDPrice = marketPair["Rate"].toDouble();
                currentUSDBalancePrice = currentBalance * currentUSDPrice / 1000000;
            }
            this->ui->labelUSD1->setText(QSTRING_DOUBLE(currentUSDPrice));
            this->ui->labelUSD->setText(QSTRING_DOUBLE(currentUSDBalancePrice));
        }
    }
예제 #22
0
void MedNUSContentManager::initLessonList(QJsonDocument jsonResponse)
{
    //Receive Stuff from Network I/O
    QJsonArray *lessonArray = new QJsonArray(jsonResponse.array());
    QJsonArray::ConstIterator curLesson = lessonArray->begin();

    while(curLesson!=lessonArray->end()) {
        QJsonObject fileItem = (*curLesson).toObject();
        QString desc = fileItem["lesson_desc"].toString();
        QString owner = fileItem["lesson_owner_domain"].toString() + "\\" + fileItem["lesson_owner"].toString();
        QStringList content = fileItem["file_list"].toString().split(QRegExp("[{}\",]"),
                                                                     QString::SplitBehavior::SkipEmptyParts);
        //Account for NULL cases
        if(content.size() == 1 && content[0] =="NULL")
            content.clear();

        emit callAddLesson(fileItem["lesson_title"].toString(), desc, owner, content, "");

        curLesson++;
    }

    QStringList content;
    content.push_back("/mednus/lesson1/videos/Skull Anatomy (1 of 5)- Superior, Posterior and Lateral Views -- Head and Neck Anatomy 101.mp4");
    content.push_back("/mednus/lesson1/videos/Osteology of the Skull- 12 Newborn Skull.mp4");
    content.push_back("/mednus/lesson1/pdf/Functional anatomy of skull.pdf");
    content.push_back("/mednus/lesson1/models/model2");
    content.push_back("/mednus/lesson1/quiz/Quiz - The Skull.qiz");
    emit callAddLesson("Functional Anatomy of the Skull","Professor Gopal","Anatomy Department",content, "/mednus/lesson1/story");

    QStringList content2;
    content2.push_back("/mednus/lesson2/pdf/axial_lecture_2.pdf");
    content2.push_back("/mednus/lesson2/videos/Osteology of the Skull- 7 The Face (1).mp4");
    content2.push_back("/mednus/lesson1/models/model1");
    emit callAddLesson("Osteology of the Skull","A/Professor Tan","Anatomy Department",content2, "");

    content2.clear();
    content2.push_back("/mednus/lesson2/pdf/axial_lecture_2.pdf");
    content.push_back("/mednus/lesson1/pdf/Functional anatomy of skull.pdf");
    content2.push_back("/mednus/lesson1/videos/Osteology of the Skull- 12 Newborn Skull.mp4");
    emit callAddLesson("Skull Osteology II","A/Professor Tan","Anatomy Department",content2, "");
    //openLastView(content);
}
예제 #23
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;
}
예제 #24
0
QVariantList APIHelper::jsonToVariantList(const QByteArray &json)
{
#ifdef QT_DEBUG
        qDebug() << "Start to parse JSON into QVariantMap.";
#endif
        QString jsonString(json);

#ifdef QT_DEBUG
        qDebug() << json;
#endif
        QJsonParseError err;

        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8(), &err);

#ifdef QT_DEBUG
        qDebug() << err.errorString();
#endif

    return jsonDoc.array().toVariantList();
}
예제 #25
0
파일: map.cpp 프로젝트: matteli/histemul
void Map::slotProvinceUpdateReply(QNetworkReply* reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
       QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll());
       QJsonArray json_array = jsonResponse.array();
       QStringList s0 = mStripe0.split('.');
       QStringList s1 = mStripe1.split('.');
       QList<QStringList> stripes;
       stripes << s0 << s1;
       //QStringList f = fill().split('.');
       foreach (const QJsonValue & value, json_array){
            QJsonObject obj = value.toObject();
            int id = obj["_id"].toInt();
            for (int i=0; i<stripes.size(); ++i)
            {
                QStringList stripe = stripes.at(i);
                inspectJson(0, obj, id, stripe, i);
            }
        }
예제 #26
0
void BackStageForm::loadExamples()
{
	QFile index(AppDirs::examples() + QDir::separator() + "index.json");

	if ( ! index.exists())
	{
		qDebug() << "BackStageForm::loadExamples();  index not found\n";
		return;
	}

	index.open(QFile::ReadOnly);
	if ( ! index.isOpen())
	{
		qDebug() << "BackStageForm::loadExamples();  index could not be opened\n";
		return;
	}

	QByteArray bytes = index.readAll();
	QJsonParseError error;

	QJsonDocument doc = QJsonDocument::fromJson(bytes, &error);

	if (error.error != QJsonParseError::NoError)
	{
		qDebug() << "BackStageForm::loadExamples();  JSON parse error : " << error.errorString() << "\n";
		return;
	}

	QJsonArray examples = doc.array();

	for (int i = examples.size() - 1; i >= 0; i--)
	{
		QJsonObject example = examples.at(i).toObject();
		QString path = AppDirs::examples() + QDir::separator() + example["path"].toString();
		QString name = example["name"].toString();
		QString description = example["description"].toString();

		ui->exampleDataSets->addDataSetOption(path, name, description);
	}

}
예제 #27
0
// @brief 读取存档文件
void DynamicData::loadUserSaveFile(const QString fileName)
{
    QFile file(fileName);
    // 当存档文件不存在时,丢出异常,重新建立存档
    if(!file.exists()){
        TyLogWarning("UserSaveFile is not exists.fileName: %s", fileName.toUtf8().data());
        resetUserSaveFile();
        return;
    }
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
        TyLogFatal("Open Save File Failure");
        resetUserSaveFile();
        return;
    }
    
    _userSaveData.clear();
    
    QJsonParseError parseErr;
    QJsonDocument doc = QJsonDocument::fromJson(file.readAll(),&parseErr);
    if(parseErr.error != QJsonParseError::NoError)
         throw QString("Save File failure!");
    if(!doc.isArray())
        throw QString("Save File Failure!");
    QJsonArray tabArr = doc.array();
    for(int i = 0; i < DEFAULT_TAB_COUNT; ++i){// 每一个Tab
        QVector<AppBtnInfo> btnVector;
        QJsonValue val = tabArr.at(i);
        if(!val.isArray())
            throw QString("Save File Failure!");
        QJsonArray arr = val.toArray();
        for(int i = 0; i < arr.count(); ++i){
            QJsonValue valObj = arr.at(i);
            if(!valObj.isObject())
                throw QString("Save File Failure!");
            QJsonObject obj = valObj.toObject();
            AppBtnInfo appBtnInfo(obj[KEY_APP_NAME].toString(), obj[KEY_FILE_NAME].toString(), obj[KEY_HOT_KEY].toString());
            btnVector.append(appBtnInfo);
        }
        _userSaveData.append(btnVector);
    }
}
void QTweetUserStatusesFollowers::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isObject()) {
        if (m_usesCursoring) {
            QJsonObject respJsonObject = jsonDoc.object();

            QJsonArray userListJsonArray = respJsonObject["users"].toArray();

            QList<QTweetUser> userList = QTweetConvert::jsonArrayToUserInfoList(userListJsonArray);

            QString nextCursor = respJsonObject["next_cursor_str"].toString();
            QString prevCursor = respJsonObject["previous_cursor_str"].toString();

            emit parsedFollowersList(userList, nextCursor, prevCursor);
        } else {
            QList<QTweetUser> userList = QTweetConvert::jsonArrayToUserInfoList(jsonDoc.array());

            emit parsedFollowersList(userList);
        }
    }
}
예제 #29
0
std::vector<CRHInfo>
CRestWorker::get_ssh_containers(int &http_code,
                                int &err_code,
                                int &network_error) {
  QJsonDocument doc = get_request_json_document("containers", http_code, err_code, network_error);
  if (err_code != 0) return std::vector<CRHInfo>();

  if (!doc.isArray()) {
    err_code = RE_NOT_JSON_OBJECT;
    return std::vector<CRHInfo>();
  }

  std::vector<CRHInfo> lst_res;
  QJsonArray arr = doc.array();

  for (auto i = arr.begin(); i != arr.end(); ++i) {
    if (i->isNull() || !i->isObject()) continue;
    lst_res.push_back(CRHInfo(i->toObject()));
  }
  return lst_res;
}
예제 #30
0
int Evaluator::target(const QString &target)
{
	for (LangSpec *spec : langSpecs)
	{
		int ret = this->target(target, spec);
		if (ret != 0)
			return ret;
	}
	if (target == "deploy" && mgr)
	{
		bool gameExists = false; int gameid = -1;
		QPair<QString, QByteArray> result = apiGetCall("/api/gametypes");
		if (!result.first.isEmpty())
		{
			fprintf(stderr, "Fehler beim Abrufen der Spiele: %s\n", qPrintable(result.first));
			return 1;
		}
		QJsonDocument jsonDoc = QJsonDocument::fromJson(result.second);
		QJsonArray gametypes = jsonDoc.array();
		for (int i = 0; i < gametypes.size(); i++)
		{
			QJsonObject gametype = gametypes[i].toObject();
			
			if (gametype.value("name").toString() == instructions().values().value("NAME"))
			{
				gameExists = true;
				gameid = gametype.value("id").toInt();
			}
			
		}
		
		if (gameExists)
		{
			QString error = apiGetCall("/api/make_data_container/" + QString::number(gameid)).first;
			if (!error.isEmpty())
				fprintf(stderr, "Fehler beim Bauen dese Daten-Containers (wird von Codr benötigt): %s\n", qPrintable(error));
		}
	}
	return 0;
}