void syncRoles() { QJsonObject firstObject(_data.first().toObject()); // TODO it expects certain data structure in all objects, add way to specify roles if (!_roles.count()) { _roles.reserve(firstObject.count()); _roles[SyncedRole] = EnginioString::_synced; // TODO Use a proper name, can we make it an attached property in qml? Does it make sense to try? _roles[CreatedAtRole] = EnginioString::createdAt; _roles[UpdatedAtRole] = EnginioString::updatedAt; _roles[IdRole] = EnginioString::id; _roles[ObjectTypeRole] = EnginioString::objectType; _rolesCounter = LastRole; } // estimate additional dynamic roles: QSet<QString> definedRoles = _roles.values().toSet(); for (QJsonObject::const_iterator i = firstObject.constBegin(); i != firstObject.constEnd(); ++i) { const QString key = i.key(); if (definedRoles.contains(key)) { // we skip predefined keys so we can keep constant id for them if (Q_UNLIKELY(key == EnginioString::_synced)) qWarning("EnginioModel can not be used with objects having \"_synced\" property. The property will be overriden."); } else _roles[_rolesCounter++] = i.key(); } }
bool QEnginioObjectShared::isModified() const { QJsonObject::const_iterator i; for (i = iJsonObject.begin(); i != iJsonObject.end(); ++i) { if (i.key() == QtCloudServicesConstants::id || i.key() == QtCloudServicesConstants::objectType) { continue; } if (!iPersistentJsonObject.contains(i.key())) { return true; // field added } if (iPersistentJsonObject.value(i.key()) != i.value()) { return true; // field changed } } for (i = iPersistentJsonObject.begin(); i != iPersistentJsonObject.end(); ++i) { if (!iPersistentJsonObject.contains(i.key())) { return true; // field removed } } return false; }
void dialogGameStats::updateGameStatsFromJsonResponse(const QJsonObject &jsonObject) { if (!jsonObject["top"].isNull()) { for(QJsonObject::const_iterator iter = jsonObject.begin(); iter != jsonObject.end(); ++iter) { if (iter.key() == "top") { // while (this->ui->tableWidgetGameStats->rowCount() > 0) // { // this->ui->tableWidgetGameStats->removeRow(0); // } this->ui->treeWidgetGameStats->clear(); //this->ui->tableWidgetGameStats->setColumnCount(2); // this->ui->tableWidgetGameStats->horizontalHeaderItem(0)->setText("Viewers"); // this->ui->tableWidgetGameStats->horizontalHeaderItem(1)->setText("Game"); for (int i = 0; i <= iter.value().toArray().size(); i++) { // qDebug() << iter.value().toArray().at(i).toObject()["game"].toObject()["name"].toString(); // qDebug() << iter.value().toArray().at(i).toObject()["viewers"].toDouble(); if (iter.value().toArray().at(i).toObject()["game"].toObject()["name"].toString() != "") { QTreeWidgetItem * item = new QTreeWidgetItem(); item->setText(0,QString::number(i+1)); item->setText(1,QString::number(iter.value().toArray().at(i).toObject()["viewers"].toDouble())); item->setText(2,iter.value().toArray().at(i).toObject()["game"].toObject()["name"].toString()); item->setTextColor(1, QColor(85,85,255)); this->ui->treeWidgetGameStats->addTopLevelItem(item); } } } } } }
v8::Local<v8::Object> QV8JsonWrapper::fromJsonObject(const QJsonObject &object) { v8::Local<v8::Object> v8object = v8::Object::New(); for (QJsonObject::const_iterator it = object.begin(); it != object.end(); ++it) v8object->Set(QJSConverter::toString(it.key()), fromJsonValue(it.value())); return v8object; }
QMap<QString, QMap<QString, QString>> Info::getServiceServerAddressMeta() { QString filename = getAddressMetaFilename(); QByteArray json("[]"); if(Filesystem::fileExist(filename)){ json = Filesystem::fileGetContents(filename); } QJsonParseError parserError; QJsonDocument doc = QJsonDocument::fromJson(json, &parserError); QMap<QString, QMap<QString, QString>> ret; if(parserError.error == QJsonParseError::NoError){ QJsonArray array = doc.array(); QJsonArray::const_iterator ait = array.constBegin(); QJsonArray::const_iterator aendmarker = array.constEnd(); while(ait != aendmarker){ QJsonValue v = *ait; if(v.isObject()){ QJsonObject item = v.toObject(); QJsonObject::const_iterator oit = item.constBegin(); QJsonObject::const_iterator oendmarker = item.constEnd(); QMap<QString, QString> dataItem; while(oit != oendmarker){ dataItem.insert(oit.key(), oit.value().toString()); oit++; } ret.insert(dataItem.value("key"), dataItem); } ait++; } } return ret; }
void EnginioBaseModelPrivate::syncRoles() { QJsonObject firstObject(_data.first().toObject()); if (!_roles.count()) { _roles.reserve(firstObject.count()); _roles[QtCloudServices::SyncedRole] = QtCloudServicesConstants::_synced; // TODO Use a proper name, can we make it an attached property in qml? Does it make sense to try? _roles[QtCloudServices::CreatedAtRole] = QtCloudServicesConstants::createdAt; _roles[QtCloudServices::UpdatedAtRole] = QtCloudServicesConstants::updatedAt; _roles[QtCloudServices::IdRole] = QtCloudServicesConstants::id; _roles[QtCloudServices::ObjectTypeRole] = QtCloudServicesConstants::objectType; _rolesCounter = QtCloudServices::CustomPropertyRole; } // check if someone does not use custom roles QHash<int, QByteArray> predefinedRoles = q->roleNames(); foreach (int i, predefinedRoles.keys()) { if (i < QtCloudServices::CustomPropertyRole && i >= QtCloudServices::SyncedRole && predefinedRoles[i] != _roles[i].toUtf8()) { qWarning("Can not use custom role index lower then QtCloudServices::CustomPropertyRole, but '%i' was used for '%s'", i, predefinedRoles[i].constData()); continue; } _roles[i] = QString::fromUtf8(predefinedRoles[i].constData()); } // estimate additional dynamic roles: QSet<QString> definedRoles = _roles.values().toSet(); QSet<int> definedRolesIndexes = predefinedRoles.keys().toSet(); for (QJsonObject::const_iterator i = firstObject.constBegin(); i != firstObject.constEnd(); ++i) { const QString key = i.key(); if (definedRoles.contains(key)) { // we skip predefined keys so we can keep constant id for them if (Q_UNLIKELY(key == QtCloudServicesConstants::_synced)) { qWarning("EnginioModel can not be used with objects having \"_synced\" property. The property will be overriden."); } } else { while (definedRolesIndexes.contains(_rolesCounter)) { ++_rolesCounter; } _roles[_rolesCounter++] = i.key(); } } }
static PyObject *convertFrom_QJsonObject(void *sipCppV, PyObject *sipTransferObj) { QJsonObject *sipCpp = reinterpret_cast<QJsonObject *>(sipCppV); #line 28 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtCore/qjsonobject.sip" PyObject *d = PyDict_New(); if (!d) return 0; QJsonObject::const_iterator it = sipCpp->constBegin(); QJsonObject::const_iterator end = sipCpp->constEnd(); while (it != end) { QString *k = new QString(it.key()); PyObject *kobj = sipConvertFromNewType(k, sipType_QString, sipTransferObj); if (!kobj) { delete k; Py_DECREF(d); return 0; } QJsonValue *v = new QJsonValue(it.value()); PyObject *vobj = sipConvertFromNewType(v, sipType_QJsonValue, sipTransferObj); if (!vobj) { delete v; Py_DECREF(kobj); Py_DECREF(d); return 0; } int rc = PyDict_SetItem(d, kobj, vobj); Py_DECREF(vobj); Py_DECREF(kobj); if (rc < 0) { Py_DECREF(d); return 0; } ++it; } return d; #line 182 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtCore/sipQtCoreQJsonObject.cpp" }
void GetFaceResourceTest::testFaces(const QString& fileName) { QString base = testResources + QDir::separator() + fileName; QFile file(base + ".jpg"); QJsonDocument current; int status = faceResource->getJSONFaces(&file, current); file.close(); QCOMPARE(HttpHeaders::STATUS_SUCCESS, status); QFile jsonFile(base + ".json"); QVERIFY(jsonFile.exists()); jsonFile.open(QIODevice::ReadOnly | QIODevice::Text); QJsonDocument expected = QJsonDocument().fromJson(jsonFile.readAll()); jsonFile.close(); QJsonArray currentArray = current.array(); QJsonArray expectedArray = expected.array(); // Make sure we're not comparing zero to zero QVERIFY(expectedArray.size() > 0); QCOMPARE(currentArray.size(), expectedArray.size()); for (int i=0; i<currentArray.size(); ++i) { QJsonObject cFaceParts = currentArray[i].toObject(); QJsonObject eFaceParts = expectedArray[i].toObject(); QJsonObject cFace = eFaceParts["face"].toObject(); QJsonObject eFace = eFaceParts["face"].toObject(); compareDoubles(cFace["x1"].toDouble(), eFace["x1"].toDouble(), 0.0001); compareDoubles(cFace["x2"].toDouble(), eFace["x2"].toDouble(), 0.0001); compareDoubles(cFace["y1"].toDouble(), eFace["y1"].toDouble(), 0.0001); compareDoubles(cFace["y2"].toDouble(), eFace["y2"].toDouble(), 0.0001); QCOMPARE(cFaceParts["pose"], eFaceParts["pose"]); QCOMPARE(cFaceParts["model"], eFaceParts["model"]); QJsonObject cParts = cFaceParts["parts"].toObject(); QJsonObject eParts = eFaceParts["parts"].toObject(); QCOMPARE(cParts.size(), eParts.size()); for (QJsonObject::const_iterator cIter = cParts.constBegin(); cIter != cParts.constEnd(); ++cIter) { QJsonArray cSubpart = cIter.value().toArray(); QJsonArray eSubpart = cParts[cIter.key()].toArray(); QCOMPARE(cSubpart.size(), eSubpart.size()); for (int i=0; i<cSubpart.size(); ++i) { QJsonObject cPart = cSubpart[i].toObject(); QJsonObject ePart = eSubpart[i].toObject(); compareDoubles(cPart["x"].toDouble(), ePart["x"].toDouble(), 0.0001); compareDoubles(cPart["y"].toDouble(), ePart["y"].toDouble(), 0.0001); QCOMPARE(cPart["num"], ePart["num"]); } } } }
void QJsonView::buildObject(const QString& name, const QJsonObject &obj, QTreeWidgetItem *parent) { QTreeWidgetItem *item = createItem(name + (!name.isEmpty()? " " : "") + "{...}", parent, TYPE_ITEM_OBJECT); QJsonObject::const_iterator iterator = obj.begin(); while( iterator != obj.end() ) { addItem(iterator.key(), iterator.value(), item); ++iterator; } }
QStringList DBSchema::fields(QString tableName) const { QJsonArray table = jsondoc.object().value(tableName).toArray(); QStringList li; for (int i = 0; i < table.size(); ++i){ QJsonObject field = table.at(i).toObject(); QJsonObject::const_iterator it = field.constBegin(); li.append( it.key() ); } return li; }
QString DBSchema::type(QString tableName, QString fieldName) const { QJsonArray table = jsondoc.object().value(tableName).toArray(); for (int i = 0; i < table.size(); ++i){ QJsonObject field = table.at(i).toObject(); QJsonObject::const_iterator it = field.constBegin(); if (it.key() == fieldName ){ return it.value().toString(); } } return QString(); }
QV4::ReturnedValue JsonObject::fromJsonObject(ExecutionEngine *engine, const QJsonObject &object) { Scope scope(engine); Scoped<Object> o(scope, engine->newObject()); ScopedString s(scope); ScopedValue v(scope); for (QJsonObject::const_iterator it = object.begin(); it != object.end(); ++it) { v = fromJsonValue(engine, it.value()); o->put((s = engine->newString(it.key())).getPointer(), v); } return o.asReturnedValue(); }
void XSAppBuilder::cmopileJsonObject(const QJsonObject &obj) { QJsonObject::const_iterator it = obj.constBegin(); while(it != obj.constEnd()) { if(root.contains(it.key())) { //暂时不需要json } it++; } }
void AddonsManager::loadUserScripts() { qDeleteAll(m_userScripts.values()); m_userScripts.clear(); QHash<QString, bool> enabledScripts; QFile file(SessionsManager::getWritableDataPath(QLatin1String("scripts/scripts.json"))); if (file.open(QIODevice::ReadOnly)) { const QJsonObject settings(QJsonDocument::fromJson(file.readAll()).object()); QJsonObject::const_iterator iterator; for (iterator = settings.constBegin(); iterator != settings.constEnd(); ++iterator) { enabledScripts[iterator.key()] = iterator.value().toObject().value(QLatin1String("isEnabled")).toBool(false); } file.close(); } const QList<QFileInfo> scripts(QDir(SessionsManager::getWritableDataPath(QLatin1String("scripts"))).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)); for (int i = 0; i < scripts.count(); ++i) { const QString path(QDir(scripts.at(i).absoluteFilePath()).filePath(scripts.at(i).fileName() + QLatin1String(".js"))); if (QFile::exists(path)) { UserScript *script(new UserScript(path, m_instance)); script->setEnabled(enabledScripts.value(scripts.at(i).fileName(), false)); m_userScripts[scripts.at(i).fileName()] = script; } else { Console::addMessage(QCoreApplication::translate("main", "Failed to find User Script file: %1").arg(path), Console::OtherCategory, Console::WarningLevel); } } m_areUserScripsInitialized = true; }
void XSAppBuilder::compileObjectProperty(const QString &qName, const QXmlAttributes &atts, xsObject *object) { if(root.contains(qName)) { QJsonObject obj = root.value(qName).toObject(); QJsonObject::const_iterator it = obj.constBegin(); while(it != obj.constEnd()) { if(it.key() == "prototype") { it++; continue; } if(it.key() == "@inherit") { compileObjectProperty(it.value().toString().toLower(), atts, object); } else if(it.value().isObject()) { if(atts.value(it.key()).isEmpty()) { it++; continue; } QJsonObject subObj = it.value().toObject(); if(subObj.contains("type")) { xsValue property; transformValue(subObj, &property, atts.value(it.key()).remove(" "), it.key()); object->setProperty(it.key().toStdString().c_str(), &property); if(it.key() == "position") { qDebug()<<it.key().toStdString().c_str(); qDebug()<<property.type; qDebug()<<property.data.n; } } } it ++; } } }
void XSAppBuilder::createPropertyObject(const QString &proName, const QString &proData, xsObject *proObject) { if(proObject == NULL) { return; } if(root.contains(proName)) { QStringList list = proData.split(";", QString::SkipEmptyParts); QJsonObject obj = root.value(proName).toObject(); QJsonObject::const_iterator it = obj.constBegin(); while(it != obj.constEnd()) { if(it.key() == "prototype" || it.key() == "@prototype") { it++; continue; } for(int i = 0; i < list.size(); i++) { if(list.at(i).contains(it.key())) { if(it.key() == "@inherit") { createPropertyObject(it.value().toString(), proData, proObject); } else { QJsonObject subObj = it.value().toObject(); QStringList dataList = list.at(i).split(":",QString::SkipEmptyParts); if(dataList.size() == 2) { xsValue property; transformValue(subObj, &property, dataList.at(1), it.key()); proObject->setProperty(it.key().toStdString().c_str(), &property); } } } } it++; } } return; }
static std::shared_ptr<AndroidStyle> loadAndroidStyle(QPalette *defaultPalette) { std::shared_ptr<AndroidStyle> style(new AndroidStyle); style->m_styleData = AndroidStyle::loadStyleData(); if (style->m_styleData.isEmpty()) return std::shared_ptr<AndroidStyle>(); for (QJsonObject::const_iterator objectIterator = style->m_styleData.constBegin(); objectIterator != style->m_styleData.constEnd(); ++objectIterator) { QString key = objectIterator.key(); QJsonValue value = objectIterator.value(); if (!value.isObject()) { qWarning("Style.json structure is unrecognized."); continue; } QJsonObject item = value.toObject(); QJsonObject::const_iterator attributeIterator = item.find(QLatin1String("qtClass")); QByteArray qtClassName; if (attributeIterator != item.constEnd()) { // The item has palette and font information for a specific Qt Class (e.g. QWidget, QPushButton, etc.) qtClassName = attributeIterator.value().toString().toLatin1(); } const int ft = fontType(key); if (ft > -1 || !qtClassName.isEmpty()) { // Extract font information QFont font; // Font size (in pixels) attributeIterator = item.find(QLatin1String("TextAppearance_textSize")); if (attributeIterator != item.constEnd()) font.setPixelSize(int(attributeIterator.value().toDouble())); // Font style attributeIterator = item.find(QLatin1String("TextAppearance_textStyle")); if (attributeIterator != item.constEnd()) { const int style = int(attributeIterator.value().toDouble()); font.setBold(style & textStyle_bold); font.setItalic(style & textStyle_italic); } // Font typeface attributeIterator = item.find(QLatin1String("TextAppearance_typeface")); if (attributeIterator != item.constEnd()) { QFont::StyleHint styleHint = QFont::AnyStyle; switch (int(attributeIterator.value().toDouble())) { case typeface_sans: styleHint = QFont::SansSerif; break; case typeface_serif: styleHint = QFont::Serif; break; case typeface_monospace: styleHint = QFont::Monospace; break; } font.setStyleHint(styleHint, QFont::PreferMatch); } if (!qtClassName.isEmpty()) style->m_QWidgetsFonts.insert(qtClassName, font); if (ft > -1) { style->m_fonts.insert(ft, font); if (ft == QPlatformTheme::SystemFont) QGuiApplication::setFont(font); } // Extract font information } const int pt = paletteType(key); if (pt > -1 || !qtClassName.isEmpty()) { // Extract palette information QPalette palette = *defaultPalette; attributeIterator = item.find(QLatin1String("defaultTextColorPrimary")); if (attributeIterator != item.constEnd()) palette.setColor(QPalette::WindowText, QRgb(int(attributeIterator.value().toDouble()))); attributeIterator = item.find(QLatin1String("defaultBackgroundColor")); if (attributeIterator != item.constEnd()) palette.setColor(QPalette::Background, QRgb(int(attributeIterator.value().toDouble()))); attributeIterator = item.find(QLatin1String("TextAppearance_textColor")); if (attributeIterator != item.constEnd()) setPaletteColor(attributeIterator.value().toObject().toVariantMap(), palette, QPalette::WindowText); attributeIterator = item.find(QLatin1String("TextAppearance_textColorLink")); if (attributeIterator != item.constEnd()) setPaletteColor(attributeIterator.value().toObject().toVariantMap(), palette, QPalette::Link); attributeIterator = item.find(QLatin1String("TextAppearance_textColorHighlight")); if (attributeIterator != item.constEnd()) palette.setColor(QPalette::Highlight, QRgb(int(attributeIterator.value().toDouble()))); if (pt == QPlatformTheme::SystemPalette) *defaultPalette = style->m_standardPalette = palette; if (pt > -1) style->m_palettes.insert(pt, palette); // Extract palette information } } return style; }
void XSAppBuilder::transformValue(const QJsonObject &subObj, xsValue *property, const QString &data, const QString &name) { if(subObj.value("type").toString() == "int") { property->type = XS_VALUE_INT32; property->data.n = data.toInt(); } else if(subObj.value("type").toString() == "boolean") { property->type = XS_VALUE_BOOL; if(data == "true") property->data.n = true; else property->data.n = false; } else if(subObj.value("type").toString() == "hashcode") { property->type = XS_VALUE_UINT32; property->data.n = data.toInt(); } else if(subObj.value("type").toString() == "string") { property->type = XS_VALUE_STRING; property->data.s = const_cast<char *>(data.toStdString().c_str()); } else if(subObj.value("type").toString() == "text") { property->type = XS_VALUE_TEXT; #ifdef XS_UNICODE property->data.t = const_cast<xsTChar *>(data.toStdWString().c_str()); #else property->data.s = const_cast<char *>(data.toStdString().c_str()); #endif } else if(subObj.value("type").toString() == "array")//功能可能有问题 { QString regex = subObj.value(("regex")).toString(); QString subStringType = subObj.value("stringType").toString(); bool toText = false; if(!subStringType.isEmpty() && subStringType == "text") { toText = true; } if(regex.isEmpty()) { if(toText) { property->type = XS_VALUE_TEXT; #ifdef XS_UNICODE property->data.t = const_cast<xsTChar *>(data.toStdWString().c_str()); #else property->data.s = const_cast<char *>(data.toStdString().c_str()); #endif } else { property->type = XS_VALUE_STRING; property->data.s = const_cast<char *>(data.toStdString().c_str()); } return; } xsArray *ar = xsArrayCreate(2); property->type = XS_VALUE_ARRAY; property->data.array = ar; if(regex.length() == 0) { xsValue str; str.type = XS_VALUE_STRING; str.data.s = const_cast<char *>(data.toStdString().c_str()); xsArrayAdd(ar, &str); } else { QStringList strs = data.split(regex); for(int i = 0; i < strs.size(); i++) { if(toText) { xsValue str; str.type = XS_VALUE_TEXT; #ifdef XS_UNICODE str.data.t = const_cast<xsTChar *>(strs.at(i).toStdWString().c_str()); #else str.data.s = const_cast<char *>(strs.at(i).toStdString().c_str()); #endif } else { xsValue str; str.type = XS_VALUE_STRING; str.data.s = const_cast<char *>(strs.at(i).toStdString().c_str()); xsArrayAdd(ar, &str); } } } } else if(subObj.value("type").toString() == "enum") { property->type = XS_VALUE_INT32; QJsonObject enumObj = subObj.value("enum").toObject(); property->data.n = enumObj.value(data).toInt(); } else if(subObj.value("type").toString() == "combine") { property->type = XS_VALUE_UINT32; property->data.n = 0; QJsonObject enumObj = subObj.value("enum").toObject(); QJsonObject::const_iterator enumIt = enumObj.constBegin(); while(enumIt != enumObj.constEnd()) { if(data.contains(enumIt.key())) { property->data.n |= enumIt.value().toInt(); } enumIt++; } } else if(subObj.value("type").toString() == "object") { property->type = XS_VALUE_OBJECT; xsObject *proObject = static_cast<xsObject *>(xsObject::createInstance()); property->data.obj = proObject; QString realProName = name; QStringList list = data.split(";", QString::SkipEmptyParts); for(int i = 0; i < list.size(); i++) { if(list.at(i).contains("prototype")) { QStringList dataList = list.at(i).split(":",QString::SkipEmptyParts); realProName = dataList.at(1); } } xsValue prototype; prototype.type = XS_VALUE_STRING; prototype.data.s = const_cast<char *>(realProName.toStdString().c_str()); proObject->setProperty("prototype", &prototype); createPropertyObject(realProName, data, proObject); } else if(subObj.value("type").toString() == "any") { property->type = XS_VALUE_UNDEFINE; property->data.ptr = const_cast<char *>(data.toStdString().c_str()); } }
void LangsTranslation::read(const QJsonObject &json){ QJsonObject::const_iterator i; for (i = json.begin(); i != json.end(); i++){ m_names[i.key().toInt()] = i.value().toString(); } }
void MapWidget::loadMap(QString const & filename) { // read file QFile qf(filename); if (!qf.open(QIODevice::ReadOnly)) throw qf.errorString(); QByteArray jsn_in = qf.readAll(); qf.close(); if (jsn_in.isEmpty()) throw QString("Empty file"); // parse file QJsonDocument jsn_doc; if (filename.endsWith("json")) { jsn_doc = QJsonDocument::fromJson(jsn_in); } else { jsn_doc = QJsonDocument::fromBinaryData(jsn_in); } if (jsn_doc.isNull()) throw QString("Failed to validate JSON data"); if (!jsn_doc.isObject()) throw QString("Top level JSON value is not an object"); QJsonObject jsn_map = jsn_doc.object(); // load generic map info QJsonObject::const_iterator it; it = jsn_map.find("rows"); if (it == jsn_map.end()) throw QString("File not contains 'rows'"); if (!it.value().isDouble()) throw QString("'rows' is not a number"); int rows = int(it.value().toDouble()); it = jsn_map.find("cols"); if (it == jsn_map.end()) throw QString("File not contains 'cols'"); if (!it.value().isDouble()) throw QString("'cols' is not a number"); int cols = int(it.value().toDouble()); // load tiles FIXME: each key must be in [0; jsn_tiles.size()-1] or assertion happens it = jsn_map.find("tiles"); if (it == jsn_map.end()) throw QString("File not contains 'tiles'"); if (!it.value().isObject()) throw QString("'cells' is not an object"); QJsonObject jsn_tiles = it.value().toObject(); QVector<MapTile> tiles(jsn_tiles.size()); QSize tileSize(-1, -1); int prev_tile_id = -1; for(QJsonObject::const_iterator i = jsn_tiles.begin(); i != jsn_tiles.end(); ++i) { int tile_id = i.key().toInt(); if (tile_id - prev_tile_id != 1) throw QString("Non-monotonic tile keys"); if (!i.value().isString()) throw QString("Incorrect tile's path"); QImage im(i.value().toString()); if (im.isNull()) throw QString("Can't open image"); if (tileSize.isEmpty()) { tileSize = im.size(); } else if (tileSize != im.size()) { throw QString("Tile's dimensions not same"); } tiles[tile_id] = MapTile(i.value().toString(), im); prev_tile_id = tile_id; } // load cells QVector<int> cells(cols * rows); it = jsn_map.find("cells"); if (it == jsn_map.end()) throw QString("File not contains 'cells'"); if (!it.value().isArray()) throw QString("'cells' is not an array"); QJsonArray jsn_cells = it.value().toArray(); if (jsn_cells.size() != cols * rows) throw QString("Incorrect 'cells' length"); int index = -1; for(QJsonArray::const_iterator i = jsn_cells.begin(); i != jsn_cells.end(); ++i) { if (!(*i).isDouble()) throw QString("Not number in 'cells'"); int val = int((*i).toDouble()); if (val < -1 || val >= tiles.size()) throw QString("Incorrect range in 'cells'"); if (val > 0 && false == tiles[val].isValid()) throw QString("Incorrect link in 'cells'"); cells[++index] = val; } // if everything is fine mCells = cells; mTiles = tiles; mRows = rows; mCols = cols; mTileSize = tileSize; mViewportPos = QPointF(.0f, .0f); mCellUnderMouse = QPoint(-1, -1); mSelectionBegin = NULL; mSelectionEnd = NULL; mScale = 1.0f; update(); }
void BSClient::replySeriesGenresFinished() { qDebug() << "BSClient::replySeriesGenresFinished()"; QByteArray byteArray = m_reply->readAll(); if(isCaptcha(byteArray)) { loadSeriesGenres(); return; } QJsonDocument document = QJsonDocument::fromJson(byteArray); if(!document.isObject()) { Q_EMIT error(tr("JSON-Parse-Fehler: 0x0007")); return; } QHash<QString, QList<QPair<int, QString> > > seriesCategories; QJsonObject object = document.object(); for(QJsonObject::const_iterator iter = object.constBegin(); iter != object.constEnd(); iter++) { if(!iter.value().isObject()) { qDebug() << iter.value(); Q_EMIT error(tr("JSON-Parse-Fehler: 0x0008")); return; } QJsonObject object_ = iter.value().toObject(); if(!object_.contains("series")) { Q_EMIT error(tr("JSON-Parse-Fehler: 0x0009")); return; } QJsonValue value = object_.value("series"); if(!value.isArray()) { Q_EMIT error(tr("JSON-Parse-Fehler: 0x000A")); return; } QList<QPair<int, QString> > series; QJsonArray array = iter.value().toArray(); Q_FOREACH(const QJsonValue &value_, value.toArray()) { if(!value_.isObject()) { Q_EMIT error(tr("JSON-Parse-Fehler: 0x000B")); return; } QJsonObject object__ = value_.toObject(); if(!object__.contains("name")) { Q_EMIT error(tr("JSON-Parse-Fehler: 0x000C")); return; } QJsonValue idValue = object__.value("id"); if(!idValue.isDouble()) { Q_EMIT error(tr("JSON-Parse-Fehler: 0x000D")); return; } QJsonValue nameValue = object__.value("name"); if(!nameValue.isString()) { Q_EMIT error(tr("JSON-Parse-Fehler: 0x000E")); return; } series << qMakePair(idValue.toInt(), nameValue.toString()); } seriesCategories.insert(iter.key(), series); } Q_EMIT loadSeriesGenresFinished(seriesCategories); }
//------------------------------------------------------------------------------ // Name: toJson //------------------------------------------------------------------------------ QString QJsonDocument::toJson(const QJsonValue &v, JsonFormat format) const { QString b; QTextStream ss(&b, QIODevice::WriteOnly | QIODevice::Text); switch(v.type()) { case QJsonValue::Null: ss << "null"; break; case QJsonValue::Bool: ss << (v.toBool() ? "true" : "false"); break; case QJsonValue::Double: ss << v.toDouble(); break; case QJsonValue::String: ss << '"' << escapeString(v.toString()) << '"'; break; case QJsonValue::Array: { const QJsonArray a = v.toArray(); ss << "["; if(!a.empty()) { QJsonArray::const_iterator it = a.begin(); QJsonArray::const_iterator e = a.end(); ss << toJson(*it++, format); for(;it != e; ++it) { ss << ','; ss << toJson(*it, format); } } ss << "]"; } break; case QJsonValue::Object: { const QJsonObject o = v.toObject(); ss << "{"; if(!o.empty()) { QJsonObject::const_iterator it = o.begin(); QJsonObject::const_iterator e = o.end(); ss << '"' << escapeString(it.key()) << "\": " << toJson(it.value(), format); ++it; for(;it != e; ++it) { ss << ','; ss << '"' << escapeString(it.key()) << "\": " << toJson(it.value(), format); } } ss << "}"; } break; case QJsonValue::Undefined: Q_ASSERT(0); break; } return b; }