//==== SYSCACHE ==== RestOutputStruct::ExitCode WebSocket::EvaluateSyscacheRequest(const QJsonValue in_args, QJsonObject *out){ //syscache only needs a list of sub-commands at the moment (might change later) QStringList in_req; //Parse the input arguments structure if(in_args.isArray()){ in_req = JsonArrayToStringList(in_args.toArray()); } else if(in_args.isObject()){ QStringList keys = in_args.toObject().keys(); for(int i=0; i<keys.length(); i++){ in_req << JsonValueToString(in_args.toObject().value(keys[i])); } }else{ return RestOutputStruct::BADREQUEST; } //Run the Request (should be one value for each in_req) QStringList values = SysCacheClient::parseInputs(in_req); while(values.length() < in_req.length()){ values << "[ERROR]"; } //ensure lists are same length //Format the result for(int i=0; i<values.length(); i++){ if(values[i].contains(SCLISTDELIM)){ //This is an array of values from syscache QStringList vals = values[i].split(SCLISTDELIM); vals.removeAll(""); QJsonArray arr; for(int j=0; j<vals.length(); j++){ arr.append(vals[j]); } out->insert(in_req[i],arr); }else{ out->insert(in_req[i],values[i]); } } //Return Success return RestOutputStruct::OK; }
QJsonValue JsonDbReduceDefinition::addObject(JsonDbReduceDefinition::FunctionNumber functionNumber, const QJsonValue &keyValue, QJsonValue previousValue, JsonDbObject object) { initScriptEngine(); QJSValue svKeyValue = mScriptEngine->toScriptValue(keyValue); if (!mTargetValueName.isEmpty()) previousValue = previousValue.toObject().value(mTargetValueName); QJSValue svPreviousValue = mScriptEngine->toScriptValue(previousValue); QJSValue svObject = mScriptEngine->toScriptValue(static_cast<QJsonObject>(object)); QJSValueList reduceArgs; reduceArgs << svKeyValue << svPreviousValue << svObject; QJSValue reduced = mFunctions[functionNumber].call(reduceArgs); if (!reduced.isUndefined() && !reduced.isError()) { QJsonValue jsonReduced = mScriptEngine->fromScriptValue<QJsonValue>(reduced); QJsonObject jsonReducedObject; if (!mTargetValueName.isEmpty()) jsonReducedObject.insert(mTargetValueName, jsonReduced); else jsonReducedObject = jsonReduced.toObject(); return jsonReducedObject; } else { if (reduced.isError()) setError(QString::fromLatin1("Error executing %1 function: %2") .arg((functionNumber == JsonDbReduceDefinition::Add ? QStringLiteral("add") : QStringLiteral("subtract"))) .arg(reduced.toString())); return QJsonValue(QJsonValue::Undefined); } }
QJsonValue NJson::remove(QJsonValue parentValue, const QString &keysStr) { QStringList keys = keysStr.split("."); QString key = keys[0]; int index = key.toInt(); if (keys.size() == 1) { if (parentValue.isArray()) { QJsonArray array = parentValue.toArray(); array.removeAt(index); return QJsonValue(array); } else { QJsonObject object = parentValue.toObject(); object.remove(key); return QJsonValue(object); } } else { keys.pop_front(); if (parentValue.isArray()) { QJsonArray array= parentValue.toArray(); QJsonValue newValue = remove(QJsonValue(array[index]), keys.join(".")); if (array.size() <= index) { array.insert(index, newValue); } else { array[index] = newValue; } return QJsonValue(array); } else { QJsonObject object = parentValue.toObject(); object[key] = remove(QJsonValue(parentValue.toObject()[key]), keys.join(".")); return QJsonValue(object); } } }
//==== SYSADM -- Update ==== RestOutputStruct::ExitCode WebSocket::EvaluateSysadmUpdateRequest(const QJsonValue in_args, QJsonObject *out){ if(in_args.isObject()){ QStringList keys = in_args.toObject().keys(); bool ok = false; if(keys.contains("action")){ QString act = JsonValueToString(in_args.toObject().value("action")); if(act=="checkupdates"){ ok = true; out->insert("checkupdates", sysadm::Update::checkUpdates()); } if(act=="listbranches"){ ok = true; out->insert("listbranches", sysadm::Update::listBranches()); } } //end of "action" key usage //If nothing done - return the proper code if(!ok){ return RestOutputStruct::BADREQUEST; } }else{ // if(in_args.isArray()){ return RestOutputStruct::BADREQUEST; } return RestOutputStruct::OK; }
QList<FileStoreEntry*> Dropbox::readdir(QString path, QStringList &errors) { QList<FileStoreEntry*> returning; // do we have a token QString token = appsettings->cvalue(context->athlete->cyclist, GC_DROPBOX_TOKEN, "").toString(); if (token == "") { errors << tr("You must authorise with Dropbox first"); return returning; } // lets connect and get basic info on the root directory QString url("https://api.dropboxapi.com/1/metadata/auto/" + path + "?include_deleted=false&list=true"); // request using the bearer token QNetworkRequest request(url); request.setRawHeader("Authorization", (QString("Bearer %1").arg(token)).toLatin1()); QNetworkReply *reply = nam->get(request); // blocking request QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); // did we get a good response ? QByteArray r = reply->readAll(); QJsonParseError parseError; QJsonDocument document = QJsonDocument::fromJson(r, &parseError); // if path was returned all is good, lets set root if (parseError.error == QJsonParseError::NoError) { // contents ? QJsonArray contents = document.object()["contents"].toArray(); // lets look at that then for(int i=0; i<contents.size(); i++) { QJsonValue each = contents.at(i); FileStoreEntry *add = newFileStoreEntry(); //dropbox has full path, we just want the file name add->name = QFileInfo(each.toObject()["path"].toString()).fileName(); add->isDir = each.toObject()["is_dir"].toBool(); add->size = each.toObject()["bytes"].toInt(); add->id = add->name; // dates in format "Tue, 19 Jul 2011 21:55:38 +0000" add->modified = QDateTime::fromString(each.toObject()["modified"].toString().mid(0,25), "ddd, dd MMM yyyy hh:mm:ss"); returning << add; } } // all good ? return returning; }
//==== SYSADM -- iocage ==== RestOutputStruct::ExitCode WebSocket::EvaluateSysadmIocageRequest(const QJsonValue in_args, QJsonObject *out){ if(in_args.isObject()){ QStringList keys = in_args.toObject().keys(); bool ok = false; if(keys.contains("action")){ QString act = JsonValueToString(in_args.toObject().value("action")); if(act=="getdefaultsettings"){ ok = true; out->insert("getdefaultsettings", sysadm::Iocage::getDefaultSettings()); } if(act=="getjailsettings"){ ok = true; out->insert("getjailsettings", sysadm::Iocage::getJailSettings(in_args.toObject())); } if(act=="listjails"){ ok = true; out->insert("listjails", sysadm::Iocage::listJails()); } } //end of "action" key usage //If nothing done - return the proper code if(!ok){ return RestOutputStruct::BADREQUEST; } }else{ // if(in_args.isArray()){ return RestOutputStruct::BADREQUEST; } return RestOutputStruct::OK; }
bool nd::model::fetch() { nd::app* app = this->definition->application(); QJsonValue result = app->api()->get(name(), id()); qDebug() << result; qDebug() << result.toObject(); return this->loadModel(result.toObject()); }
bool mergeJsonObjects (const QJsonObject &objectMergeFrom, QJsonObject &objectMergeTo, CompareValuesJson &comparer) { LOG_DEBUG << "#"; QStringList keysMergeFrom = objectMergeFrom.keys(); int keysSize = keysMergeFrom.size(); bool anyError = false; for (int i = 0; i < keysSize; i++) { const QString &keyFrom = keysMergeFrom.at(i); if (objectMergeTo.contains(keyFrom)) { QJsonValue valueTo = objectMergeTo[keyFrom]; QJsonValue valueFrom = objectMergeFrom[keyFrom]; if (valueTo.type() != valueFrom.type()) { LOG_WARNING << "Types of Json Values do not match at key:" << keyFrom; continue; } if (valueTo.isObject()) { QJsonObject objectTo = valueTo.toObject(); QJsonObject objectFrom = valueFrom.toObject(); if (mergeJsonObjects(objectFrom, objectTo, comparer)) { valueTo = objectTo; } else { anyError = true; break; } } else if (valueTo.isArray()) { QJsonArray arrayTo = valueTo.toArray(); QJsonArray arrayFrom = valueFrom.toArray(); if (mergeJsonArrays(arrayFrom, arrayTo, comparer)) { valueTo = arrayTo; } else { anyError = true; break; } } else { valueTo = valueFrom; } objectMergeTo[keyFrom] = valueTo; } else { objectMergeTo[keyFrom] = objectMergeFrom[keyFrom]; // insert if doesn't contain } } bool mergeResult = !anyError; return mergeResult; }
Schema *MessageFacade::defineSchema(QJsonObject *root, ControllerNode *pControllerNode){ QJsonValue jsonValue = root->value(SCHEMA); if (!jsonValue.isUndefined() && jsonValue.isObject()){ QJsonObject schema= jsonValue.toObject(); QJsonValue strings =schema.value(STRING_TYPE); QJsonValue ints =schema.value(INT_TYPE); QJsonValue primaryKey = schema.value(PRIMARY_KEY); if (!strings.isUndefined() && strings.isArray() &&!ints.isUndefined() && ints.isArray() && !primaryKey.isUndefined() && primaryKey.isObject()){ QJsonArray columnaStringType = strings.toArray(); QJsonArray columnaIntsType = ints.toArray(); QJsonObject columnaPrimaryKey = primaryKey.toObject(); bool success = true; QJsonObject currentObject; for (int x = 0; x < columnaStringType.size(); x++){ currentObject =columnaStringType.at(x).toObject(); success = success && currentObject.value(currentObject.keys().at(0)).isDouble(); } for (int x = 0; x < columnaIntsType.size(); x++)success = success && columnaIntsType.at(x).isString(); QString primaryKeyName =columnaPrimaryKey.keys().at(0); qDebug() << "validando...."; if (success && validatingPrimaryKey(primaryKeyName,&columnaPrimaryKey)){ qDebug() << "validacion completa el JSON es valido"; Schema *dataSchema = StorageblockFacade::getInstance()->createSchema(1+columnaIntsType.size()+columnaStringType.size()); unsigned int sizeOfBytes = 0; QJsonObject primaryKeyScheme; primaryKeyScheme = columnaPrimaryKey.value(primaryKeyName).toObject(); if (primaryKeyName.compare(INT_TYPE) == 0)sizeOfBytes = sizeof(int); else sizeOfBytes = primaryKeyScheme.value(primaryKeyScheme.keys().at(0)).toInt()*sizeof(char); dataSchema->setSchemaOverColumn(0,primaryKeyScheme.keys().at(0).toStdString(),sizeOfBytes, (primaryKeyName.compare(INT_TYPE) == 0)?SchemeRow::INT_TYPE:SchemeRow::STRING_TYPE); int place= 1; for (int x = 0; x < columnaIntsType.size(); x++){ currentObject =columnaIntsType.at(x).toObject(); dataSchema->setSchemaOverColumn(x+(place++),columnaIntsType.at(x).toString().toStdString(),sizeof(int),SchemeRow::INT_TYPE); } for (int x = 0; x < columnaStringType.size(); x++){ currentObject =columnaStringType.at(x).toObject(); currentObject.value(currentObject.keys().at(0)).toString(); dataSchema->setSchemaOverColumn(x+place,currentObject.keys().at(0).toStdString(),sizeof(char)*currentObject.value(currentObject.keys().at(0)).toInt(),SchemeRow::STRING_TYPE); } SchemeRow row; QString type; for(int x = 0; x < dataSchema->getLenght();x++){ row = (*dataSchema)[x]; type= (row.getTypeRestrictor()==SchemeRow::INT_TYPE)?"int ":"string"; qDebug() << "| type: "<< type<< "\t| name: " << row.toString().c_str() << "\t\t| size: \t"<< row.getByteSize(); } return dataSchema; } } } return 0; }
void AppModel::handleWeatherNetworkData(QObject *replyObj) { qCDebug(requestsLog) << "got weather network data"; QNetworkReply *networkReply = qobject_cast<QNetworkReply*>(replyObj); if (!networkReply) return; if (!networkReply->error()) { foreach (WeatherData *inf, d->forecast) delete inf; d->forecast.clear(); QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); if (document.isObject()) { QJsonObject obj = document.object(); QJsonObject tempObject; QJsonValue val; if (obj.contains(QStringLiteral("weather"))) { val = obj.value(QStringLiteral("weather")); QJsonArray weatherArray = val.toArray(); val = weatherArray.at(0); tempObject = val.toObject(); d->now.setWeatherDescription(tempObject.value(QStringLiteral("description")).toString()); d->now.setWeatherIcon(tempObject.value("icon").toString()); } if (obj.contains(QStringLiteral("main"))) { val = obj.value(QStringLiteral("main")); tempObject = val.toObject(); val = tempObject.value(QStringLiteral("temp")); d->now.setTemperature(niceTemperatureString(val.toDouble())); } } } networkReply->deleteLater(); //retrieve the forecast QUrl url("http://api.openweathermap.org/data/2.5/forecast/daily"); QUrlQuery query; query.addQueryItem("q", d->city); query.addQueryItem("mode", "json"); query.addQueryItem("cnt", "5"); url.setQuery(query); QNetworkReply *rep = d->nam->get(QNetworkRequest(url)); // connect up the signal right away d->forecastReplyMapper->setMapping(rep, rep); connect(rep, SIGNAL(finished()), d->forecastReplyMapper, SLOT(map())); }
// === SYSCACHE REQUEST INTERACTION === void WebSocket::EvaluateBackendRequest(QString name, const QJsonValue args, QJsonObject *out){ QJsonObject obj; //output object if(args.isObject()){ //For the moment: all arguments are full syscache DB calls - no special ones QStringList reqs = args.toObject().keys(); if(!reqs.isEmpty()){ if(DEBUG){ qDebug() << "Parsing Inputs:" << reqs; } for(int r=0; r<reqs.length(); r++){ QString req = JsonValueToString(args.toObject().value(reqs[r])); if(DEBUG){ qDebug() << " ["+reqs[r]+"]="+req; } QStringList values; if(name.toLower()=="syscache"){values = SysCacheClient::parseInputs( QStringList() << req ); } else if(name.toLower()=="dispatcher"){values = DispatcherClient::parseInputs( QStringList() << req, AUTHSYSTEM); } values.removeAll(""); //Quick check if a list of outputs was returned if(values.length()==1 && name.toLower()=="syscache"){ values = values[0].split(SCLISTDELIM); //split up the return list (if necessary) values.removeAll(""); } if(DEBUG){ qDebug() << " - Returns:" << values; } if(values.length()<2){ out->insert(req, QJsonValue(values.join("")) ); } else{ //This is an array of outputs QJsonArray arr; for(int i=0; i<values.length(); i++){ arr.append(values[i]); } out->insert(req,arr); } } } //end of special "request" objects }else if(args.isArray()){ QStringList inputs = JsonArrayToStringList(args.toArray()); if(DEBUG){ qDebug() << "Parsing Array inputs:" << inputs; } QStringList values; if(name.toLower()=="syscache"){values = SysCacheClient::parseInputs( inputs ); } else if(name.toLower()=="dispatcher"){values = DispatcherClient::parseInputs( inputs , AUTHSYSTEM); } if(DEBUG){ qDebug() << " - Returns:" << values; } for(int i=0; i<values.length(); i++){ if(name.toLower()=="syscache" && values[i].contains(SCLISTDELIM)){ //This is an array of values from syscache QStringList vals = values[i].split(SCLISTDELIM); vals.removeAll(""); QJsonArray arr; for(int j=0; j<vals.length(); j++){ arr.append(vals[j]); } out->insert(inputs[i],arr); }else{ out->insert(inputs[i],values[i]); } } } //end array of inputs }
void ImageModel::updateRows(const QModelIndex &, int start, int end) { for (int row = start; row <= end; ++row) { QJsonValue rowData = EnginioModel::data(index(row)).value<QJsonValue>(); QString id = rowData.toObject().value("id").toString(); if (id.isEmpty() || m_images.contains(id)) continue; ImageObject *image = new ImageObject(client()); connect(image, SIGNAL(imageChanged(QString)), this, SLOT(imageChanged(QString))); m_images.insert(id, image); image->setObject(rowData.toObject()); QModelIndex changedIndex = index(row); emit dataChanged(changedIndex, changedIndex); } }
QDebug operator<<(QDebug dbg, const QJsonValue &o) { switch (o.t) { case QJsonValue::Undefined: dbg.nospace() << "QJsonValue(undefined)"; break; case QJsonValue::Null: dbg.nospace() << "QJsonValue(null)"; break; case QJsonValue::Bool: dbg.nospace() << "QJsonValue(bool, " << o.toBool() << ")"; break; case QJsonValue::Double: dbg.nospace() << "QJsonValue(double, " << o.toDouble() << ")"; break; case QJsonValue::String: dbg.nospace() << "QJsonValue(string, " << o.toString() << ")"; break; case QJsonValue::Array: dbg.nospace() << "QJsonValue(array, "; dbg.nospace() << o.toArray(); dbg.nospace() << ")"; break; case QJsonValue::Object: dbg.nospace() << "QJsonValue(object, "; dbg.nospace() << o.toObject(); dbg.nospace() << ")"; break; } return dbg.space(); }
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); }
static void overrideEntity(const QJsonValue &value, std::map<QString, Entity::Ptr> &map, Entity::List &extended) { Entity::Ptr entity {new T(value.toObject())}; map.erase(entity->text()); extended.push_back(entity); }
std::shared_ptr<const MstData> MstData::FromJsonValue(const QJsonValue& value) { auto mst_data = std::make_shared<MstData>(); auto obj = value.toObject(); if (!obj["api_mst_ship"].isArray()) throw BadJsonValue(); if (!obj["api_mst_slotitem"].isArray()) throw BadJsonValue(); for (auto& x : obj["api_mst_ship"].toArray()) { if (!x.isObject()) throw BadJsonValue(); auto x_obj = x.toObject(); MstShip ship; ship.id = GetInt(x_obj, "api_id"); ship.name = GetString(x_obj, "api_name"); mst_data->mst_ship.emplace(ship.id, ship); } for (auto& x : obj["api_mst_slotitem"].toArray()) { if (!x.isObject()) throw BadJsonValue(); auto x_obj = x.toObject(); MstSlotItem slot_item; slot_item.id = GetInt(x_obj, "api_id"); slot_item.name = GetString(x_obj, "api_name"); slot_item.type = GetIntArray(x_obj, "api_type"); mst_data->mst_slot_item.emplace(slot_item.id, slot_item); } return std::const_pointer_cast<const MstData>(mst_data); }
/*! */ QVariant SceneDocument::toVariant(const QJsonValue& value) noexcept { QVariant node; switch (value.type()) { case QJsonValue::Null: { zisc::raiseError("The json value is null."); break; } case QJsonValue::Bool: case QJsonValue::Double: case QJsonValue::String: { node = value.toVariant(); break; } case QJsonValue::Array: { node = toVariant(value.toArray()); break; } case QJsonValue::Object: { node = toVariant(value.toObject()); break; } case QJsonValue::Undefined: { zisc::raiseError("The json value is undefined."); break; } default: { zisc::raiseError("Undefined json value type is specified."); break; } } return node; }
bool Storage::getUserLimits (const QString& user, QVariantMap& target) { QString val; QFile file; QString filename = QString (CLEPSYDRA_WORKING_FOLDER).append(CLEPSYDRA_JSON_USERDATA_FILENAME); file.setFileName(filename); if ( !file.isReadable() ) { // return false; } if (file.open(QIODevice::ReadOnly | QIODevice::Text)==true) { val = file.readAll(); file.close(); } else { qDebug () << filename << "json file not found"; return false; } QJsonDocument d = QJsonDocument::fromJson(val.toUtf8()); if (d.isEmpty()) { qDebug () << "Not valid document."; return false; } QJsonObject obj = d.object(); QJsonValue mapArray = obj.value(user); if (mapArray.isUndefined()) { qDebug () << "User not found from limits."; return false; } QVariantMap dataC = mapArray.toObject().toVariantMap(); target = dataC.take(user).toMap(); return true; }
/** * @brief Algorithm::initialize Loads the corresponding QJsonObject for this algorithm * @param loader The plugin loader which loads the QJsonObject * @return True, if all went well. */ bool Algorithm::initialize(QPluginLoader *loader) { //read the QJsonObject parameter if (!loader) return false; QJsonObject tmp = loader->metaData(); if (tmp.isEmpty()) return false; QJsonValue v = tmp.value("MetaData"); if (v.isUndefined()) return false; QJsonObject o = v.toObject(); if (o.isEmpty()) return false; mId = ""; mName = ""; mDescription = ""; QString version = ""; if (o.contains("Author")) {} if (o.contains("Date")) {} if (o.contains("Name")) mName = o.value("Name").toString(); else {} //LOG WARNING if (o.contains("Version")) version = o.value("Version").toString(); else {} //LOG WARNING if (o.contains("Description")) mDescription = o.value("Description").toString(); else {} //LOG WARNING mId = mName + " " + version; if (mId.trimmed() == "") {} //LOG WARNING if (o.contains("Properties")) mDefaultParameters = o.value("Properties").toObject(); else {} //LOG WARNING return true; }
ActionsManager::ActionEntryDefinition ToolBarsManager::decodeEntry(const QJsonValue &value) { ActionsManager::ActionEntryDefinition definition; if (value.isString()) { definition.action = value.toString(); return definition; } const QJsonObject object(value.toObject()); definition.action = object.value(QLatin1String("identifier")).toString(); definition.options = object.value(QLatin1String("options")).toObject().toVariantMap(); if (object.contains(QLatin1String("actions"))) { const QJsonArray actions(object.value(QLatin1String("actions")).toArray()); for (int i = 0; i < actions.count(); ++i) { definition.entries.append(decodeEntry(actions.at(i))); } } return definition; }
bool RuleListModel::realDeserializeData() { QSettings setting("Ray Fung", "Excel JSON"); QByteArray json = setting.value("rule_list", QByteArray("[]")).toByteArray(); QJsonDocument doc = QJsonDocument::fromJson(json); ruleList.clear(); if(doc.isArray() == false) return false; QJsonArray array = doc.array(); int count = array.size(); for(int i = 0; i < count; ++i) { QJsonValue val = array.at(i); if(val.isObject() == false) return false; QJsonObject data = val.toObject(); RuleData rule; RuleItem item; rule.isEnabled = data.value("enable").toBool(true); rule.excelPath = data.value("excel_path").toString(); rule.jsonPath = data.value("json_path").toString(); item.setRule(rule); ruleList.append(item); } return true; }
QStringList JSONBreakableMarshal::toStringList(const QJsonValue& jsonValue, const QString& keypath) { // setup the string list that will hold our result QStringList result; // figure out what type of value this is so we know how to act on it if (jsonValue.isObject()) { QJsonObject jsonObject = jsonValue.toObject(); // enumerate the keys of the QJsonObject foreach(const QString& key, jsonObject.keys()) { QJsonValue childValue = jsonObject[key]; // setup the keypath for this key QString valueKeypath = (keypath.isEmpty() ? "" : keypath + ".") + key; if (childValue.isObject() || childValue.isArray()) { // recursion is required since the value is a QJsonObject or QJsonArray result << toStringList(childValue, valueKeypath); } else { // no recursion required, call our toString method to get the string representation // append the QStringList resulting from that to our QStringList result << toString(childValue, valueKeypath); } } } else if (jsonValue.isArray()) {
QString MainWindow::renderJsonValue(QJsonValue obj) { QString type = "unknown"; QString value = "unknown"; switch(obj.type()) { case QJsonValue::Bool: type = "Bool"; value = obj.toBool() ? "True" : "False"; break; case QJsonValue::Double: type = "Double"; value = QString::number(obj.toDouble()); break; case QJsonValue::String: type = "String"; value = "\""+obj.toString()+"\""; break; case QJsonValue::Array: type = "Array"; value = "["+QString::number(obj.toArray().count())+"]"; break; case QJsonValue::Object: type = "Object"; value = "{"+QString::number(obj.toObject().count())+"}"; break; default: break; } return value + " : " + type; }
JsonObject JsonObject::object(const QString& key) const { checkContains(key); QJsonValue value = o.value(key); if ( ! value.isObject()) wrongType("object", key); return JsonObject(value.toObject()); }
bool Parser::ParseGoodsMap(const QString &str, QHash<QString, Goods *> &pGoodsMap) { QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8()); if (doc.isNull()) { return false; } // json array containing all goods info QJsonArray jGoodsArray = doc.array(); if (jGoodsArray.isEmpty()) { // no goods info or error json data return false; } // parse each goods info for (int i = 0; i < jGoodsArray.size(); ++i) { QJsonValue jValue = jGoodsArray.at(i); if (jValue.isObject()) { QJsonObject jGoods = jValue.toObject(); // json of goods info // get goods info Goods *pGoods = ParseGoods(jGoods); if (pGoods) { pGoodsMap.insert(pGoods->GetBarcode(), pGoods); } } } return (pGoodsMap.size() > 0); }
void GeoNamesWeatherService::parseFile( const QByteArray& file ) { QJsonDocument jsonDoc = QJsonDocument::fromJson(file); QJsonValue weatherObservationsValue = jsonDoc.object().value(QStringLiteral("weatherObservations")); // Parse if any result exists QList<AbstractDataPluginItem*> items; if (weatherObservationsValue.isArray()) { // Add items to the list QJsonArray weatherObservationsArray = weatherObservationsValue.toArray(); for (int index = 0; index < weatherObservationsArray.size(); ++index) { QJsonObject weatherObservationObject = weatherObservationsArray[index].toObject(); AbstractDataPluginItem* item = parse(weatherObservationObject); if ( item ) { items << item; } } } else { QJsonValue weatherObservationValue = jsonDoc.object().value(QStringLiteral("weatherObservation")); QJsonObject weatherObservationObject = weatherObservationValue.toObject(); AbstractDataPluginItem* item = parse(weatherObservationObject); if ( item ) { items << item; } } emit createdItems( items ); }
QVector<Language> LoadSupportLanguage() { QFile json(":/support_languages.json"); qDebug()<<"Open File"<<json.open(QIODevice::ReadOnly); QVector<Language> supportLanguagesList; QJsonParseError json_error; QJsonDocument supportLanguages = QJsonDocument::fromJson(json.readAll(), &json_error); json.close(); if(json_error.error == QJsonParseError::NoError) { if (supportLanguages.isArray()) { QJsonArray languresArray = supportLanguages.array(); int size = languresArray.size(); for (int i = 0; i < size; ++i) { Language language; QJsonValue languageJson = languresArray.at(i); QJsonObject languageObject = languageJson.toObject(); language.Locale =languageObject.take("Locale").toString(); language.Description = languageObject.take("Description").toString(); language.LanguageCode = languageObject.take("LanguageCode").toString(); language.CountryCode = languageObject.take("CountryCode").toString(); supportLanguagesList.push_back(language); } } } return supportLanguagesList; }
void YoutubeDL::fetchAvailableFormats(QString url) { QVector<MediaFormat> formats; QJsonObject jsonObject = createJsonObject(url); QJsonArray jsonFormats = jsonObject["formats"].toArray(); QJsonArray::iterator i; for (i = jsonFormats.begin(); i != jsonFormats.end(); ++i) { QJsonValue value = *i; QJsonObject formatObject = value.toObject(); MediaFormat format; format.setFormatId(formatObject["format_id"].toString()); format.setFormat(formatObject["format"].toString()); format.setExtension(formatObject["ext"].toString()); format.setNote(formatObject["format_note"].toString()); if (formatObject.contains("height") && !formatObject["height"].isNull()) { QString resolution = QString::number(formatObject["width"].toDouble()) + "x" + QString::number(formatObject["height"].toDouble()); format.setResolution(resolution); } format.setVcodec(formatObject["vcodec"].toString().trimmed()); format.setAcodec(formatObject["acodec"].toString().trimmed()); formats.append(format); } this->formats = formats; }
void EtherIPC::handleGetSyncing() { QJsonValue jv; if ( !readReply(jv) ) { return bail(); } if ( jv.isNull() || ( jv.isBool() && !jv.toBool(false) ) ) { if ( fSyncing ) { fSyncing = false; if ( fBlockFilterID.isEmpty() ) { newBlockFilter(); } emit syncingChanged(fSyncing); } return done(); } const QJsonObject syncing = jv.toObject(); fCurrentBlock = Helpers::toQUInt64(syncing.value("currentBlock")); fHighestBlock = Helpers::toQUInt64(syncing.value("highestBlock")); fStartingBlock = Helpers::toQUInt64(syncing.value("startingBlock")); if ( !fSyncing ) { if ( !fBlockFilterID.isEmpty() ) { uninstallFilter(fBlockFilterID); fBlockFilterID.clear(); } fSyncing = true; } emit syncingChanged(fSyncing); done(); }
bool Parser::ParseOfferMap(const QString &str, QHash<QString, ItemOffer *> &pOfferMap, const QHash<QString, Goods *> &pGoodsMap) { QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8()); if (doc.isNull()) { return false; } // json array containing all offer info QJsonArray jOfferArray = doc.array(); if (jOfferArray.isEmpty()) { // no offer info or error json data return false; } // parse each offer info for (int i = 0; i < jOfferArray.size(); ++i) { QJsonValue jValue = jOfferArray.at(i); if (jValue.isObject()) { QJsonObject jOffer = jValue.toObject(); // json of offer info // get offer info ItemOffer *pOffer = ParseOffer(jOffer, pGoodsMap); if (pOffer) { pOfferMap.insert(pOffer->GetType(), pOffer); } } } return (pOfferMap.size() > 0); }