void Client::setPileNumber(const QJsonValue &pile_str){ pile_num = pile_str.toDouble(); updatePileNum(); }
MessageBoxType4::MessageBoxType4(const QJsonValue &value, QWidget *parent) : MessageBoxType4(value.toObject()["posts"].toArray()[0].toObject(), parent){}
quint64 Helpers::toQUInt64(const QJsonValue& jv) { std::string hexStr = jv.toString("0x0").remove(0, 2).toStdString(); BigInt::Vin vin(hexStr, 16); return vin.toUlong(); }
void LinkedDB::load(){ QString val; QFile file; file.setFileName("db.json"); if (!file.exists()) { throw MyExc(database, "db file does not exists!"); } if (!file.open(QIODevice::ReadOnly)) { throw MyExc(database, "problem reading the file!"); } else{ // QTextStream(stdout)<<"\n loading file!\n"; //solo x debug } val = file.readAll(); file.close(); //procedo con la lettura del file QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8()); QJsonObject all_json = doc.object(); QJsonValue all_users = all_json["users"]; //get users QJsonArray users_array = all_users.toArray(); //transform into an array for(QJsonArray::const_iterator it = users_array.begin(); it!=users_array.end(); ++it){ QJsonValue test = *it; QJsonObject obj = test.toObject(); QJsonValue user = obj["username"]; QJsonValue pass = obj["password"]; Username us( user.toString().toStdString() , pass.toString().toStdString()); QJsonValue name = obj["name"]; QJsonValue surname = obj["surname"]; QJsonValue email = obj["email"]; QJsonValue address = obj["address"]; QJsonValue tel = obj["telephon"]; QVariant birthday = QVariant(obj["birthday"]); QDate tmp = QDate::fromString(birthday.toString(),"yyyy.MM.dd"); Info info(tmp, name.toString().toStdString(),surname.toString().toStdString(),email.toString().toStdString(),address.toString().toStdString(),tel.toString().toStdString()); Info* p_info; QJsonArray _skills = obj["skills"].toArray(); for(QJsonArray::const_iterator skillIt = _skills.begin(); skillIt!=_skills.end();++skillIt){ info.addSkill((*skillIt).toString().toStdString()); } QJsonArray _languages = obj["languages"].toArray(); for(QJsonArray::const_iterator langIt = _languages.begin(); langIt!=_languages.end();++langIt){ info.addLanguage((*langIt).toString().toStdString()); } QJsonArray _interests = obj["interests"].toArray(); for(QJsonArray::const_iterator intIt = _interests.begin(); intIt!=_interests.end();++intIt){ info.addInterest((*intIt).toString().toStdString()); } QJsonArray _experiences = obj["experiences"].toArray(); for(QJsonArray::const_iterator expIt = _experiences.begin(); expIt!=_experiences.end();++expIt){ QJsonObject _exp = (*expIt).toObject(); std::string loc = _exp["location"].toString().toStdString(); std::string role = _exp["role"].toString().toStdString(); QVariant _from = QVariant(_exp["from"]); QVariant _to = QVariant(_exp["to"]); QDate from = QDate::fromString(_from.toString(),"yyyy.MM.dd"); QDate to = QDate::fromString(_to.toString(),"yyyy.MM.dd"); Experience tmp_exp(loc, role, from, to); info.addExperience(tmp_exp); } std::list<Experience> eee=info.getExperiences(); //for(std::list<Experience>::const_iterator asd=eee.begin(); asd!=eee.end();++asd) //std::cout<<(*asd)->getLocation(); p_info=&info; accountType _type = static_cast<accountType>(obj["accountType"].toInt()); Account acc(p_info ,us, _type); acc.setAvatar(obj["avatarPath"].toString().toStdString()); User* _user = NULL; SmartUser smus; switch(_type){ case 0: _user = new BasicUser(&acc); break; case 1: _user = new BusinessUser(&acc); break; case 2: _user = new ExecutiveUser(&acc); break; } smus = _user; //QTextStream(stdout)<<QString::fromStdString(smus->account()->username().getLogin())<<" "; users.push_back(smus); } //read the net of all users for(std::list<SmartUser>::const_iterator it = users.begin(); it!= users.end(); ++it){ for(int i=0; i<users_array.size(); ++i){ QJsonObject obj = users_array[i].toObject(); QJsonArray friends = obj["friends"].toArray(); if((*it)->account()->username().getLogin() == obj["username"].toString().toStdString()) { //QTextStream(stdout)<<"reading friends "<<obj["username"].toString()<<"\n"; for(int k = 0; k < friends.size(); ++k){ Username tmp_user(friends[k].toString().toStdString(), ""); (*it)->addFriend(find(tmp_user)); } } } } }
static Nuria::JsonMetaObjectReader::Error parseMethodObject (Nuria::MetaMethod::Type type, const QJsonObject &method, Nuria::RuntimeMetaObject *metaObject) { using namespace Nuria; QJsonValue annotationsValue = method.value (QStringLiteral("annotations")); QJsonValue argNamesValue = method.value (QStringLiteral("argumentNames")); QJsonValue argTypesValue = method.value (QStringLiteral("argumentTypes")); QJsonValue resultTypeValue = method.value (QStringLiteral("resultType")); QJsonValue nameValue = method.value (QStringLiteral("name")); // Type checks if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray; if (!argNamesValue.isArray ()) return JsonMetaObjectReader::MethodArgumentNamesIsNotAnArray; if (!argTypesValue.isArray ()) return JsonMetaObjectReader::MethodArgumentTypesIsNotAnArray; if (!resultTypeValue.isString ()) return JsonMetaObjectReader::MethodResultTypeIsNotAString; if (!nameValue.isString ()) return JsonMetaObjectReader::MethodNameIsNotAString; // Parse annotations Nuria::JsonMetaObjectReader::Error error; RuntimeMetaObject::AnnotationMap annotations; error = parseAnnotationsArray (annotationsValue.toArray (), annotations); if (error != Nuria::JsonMetaObjectReader::NoError) return error; // Arguments QVector< QByteArray > argNames; QVector< QByteArray > argTypes; error = parseMethodArgumentList (argNamesValue.toArray (), argTypesValue.toArray (), argNames, argTypes); if (error != Nuria::JsonMetaObjectReader::NoError) return error; // Base QByteArray name = nameValue.toString ().toLatin1 (); QByteArray resultType = resultTypeValue.toString ().toLatin1 (); // Store metaObject->addMethod (type, name, resultType, argNames, argTypes, annotations, invalidCallbackCreator); return Nuria::JsonMetaObjectReader::NoError; }
void Client::cardLock(const QJsonValue &card_str){ Self->setCardLocked(card_str.toString()); }
void Client::playAudio(const QJsonValue &name){ Bang->playAudio(name.toString()); }
void MLNodeToJsonTest::jsonObjectTest(){ MLNode n = { {"object", { {"string", "value1"}, {"key2", 100} }}, {"array", { 100, "200", false}}, {"bool", true}, {"int", 100}, {"float", 100.1}, {"null", nullptr} }; QJsonValue jv; ml::toJson(n, jv); QVERIFY(jv.isObject()); QCOMPARE(jv.toObject().size(), 6); QVERIFY(jv.toObject()["object"].isObject()); QVERIFY(jv.toObject()["object"].toObject()["string"].isString()); QCOMPARE(jv.toObject()["object"].toObject()["string"].toString(), QString("value1")); QVERIFY(jv.toObject()["object"].toObject()["key2"].isDouble()); QCOMPARE(jv.toObject()["object"].toObject()["key2"].toInt(), 100); QVERIFY(jv.toObject()["array"].isArray()); QCOMPARE(jv.toObject()["array"].toArray().size(), 3); QVERIFY(jv.toObject()["array"].toArray()[0].isDouble()); QCOMPARE(jv.toObject()["array"].toArray()[0].toInt(), 100); QVERIFY(jv.toObject()["array"].toArray()[1].isString()); QCOMPARE(jv.toObject()["array"].toArray()[1].toString(), QString("200")); QVERIFY(jv.toObject()["array"].toArray()[2].isBool()); QCOMPARE(jv.toObject()["array"].toArray()[2].toBool(), false); QVERIFY(jv.toObject()["bool"].isBool()); QCOMPARE(jv.toObject()["bool"].toBool(), true); QVERIFY(jv.toObject()["int"].isDouble()); QCOMPARE(jv.toObject()["int"].toInt(), 100); QVERIFY(jv.toObject()["float"].isDouble()); QCOMPARE(jv.toObject()["float"].toDouble(), 100.1); QVERIFY(jv.toObject()["null"].isNull()); MLNode rt; ml::fromJson(jv, rt); QCOMPARE(rt.type(), MLNode::Type::Object); QCOMPARE(rt["object"].type(), MLNode::Type::Object); QCOMPARE(rt["object"].size(), 2); QCOMPARE(rt["object"]["string"].asString(), MLNode::StringType("value1")); QCOMPARE(rt["object"]["key2"].asInt(), 100); QCOMPARE(rt["array"].size(), 3); QCOMPARE(rt["array"][0].asInt(), 100); QCOMPARE(rt["array"][1].asString(), MLNode::StringType("200")); QCOMPARE(rt["array"][2].asBool(), false); QCOMPARE(rt["bool"].asBool(), true); QCOMPARE(rt["int"].asInt(), 100); QCOMPARE(rt["float"].asFloat(), 100.1); QVERIFY(rt["null"].isNull()); }
//------------------------------------------------------------------------------ // 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; }
void SocketIOClient::parseMessage(QString message) { //qDebug() << "SocketIOClient::parseMessage" << message; QRegExp regExp("^([^:]+):([0-9]+)?(\\+)?:([^:]+)?:?([\\s\\S]*)?$", Qt::CaseInsensitive, QRegExp::RegExp2); if (regExp.indexIn(message) != -1) { QStringList captured = regExp.capturedTexts(); //qDebug() << "Found:" << regExp.capturedTexts(); int messageType = captured.at(1).toInt(); int messageId = captured.at(2).toInt(); bool mustAck = (messageId != 0); bool autoAck = mustAck && captured.at(3).isEmpty(); QString endpoint = captured.at(4); QString data = captured.at(5); /*qDebug() << "MessageType:" << messageType << "MessageId:" << messageId << "autoAck:" << autoAck << "mustAck:" << mustAck << "endpoint:" << endpoint << "data:" << data;*/ if (autoAck) { acknowledge(messageId); } switch(messageType) { case 0: //disconnect { Q_EMIT(disconnected(endpoint)); break; } case 1: //connect { m_pHeartBeatTimer->start(); Q_EMIT(connected(endpoint)); break; } case 2: //heartbeat { Q_EMIT(heartbeatReceived()); break; } case 3: //message { Q_EMIT(messageReceived(data)); break; } case 4: //json message { qDebug() << "JSON message received:" << data; break; } case 5: //event { QJsonParseError parseError; //qDebug() << "Event received:" << data; QJsonDocument document = QJsonDocument::fromJson(QByteArray(data.toLatin1()), &parseError); if (parseError.error != QJsonParseError::NoError) { qDebug() << parseError.errorString(); } else { if (document.isObject()) { QJsonObject object = document.object(); QJsonValue value = object["name"]; if (!value.isUndefined()) { QString message = value.toString(); //QVariantList arguments; QJsonArray arguments; QJsonValue argsValue = object["args"]; if (!argsValue.isUndefined() && !argsValue.isNull()) { if (argsValue.isArray()) { //QJsonArray argsArray = argsValue.toArray(); //arguments = argsArray.toVariantList(); arguments = argsValue.toArray(); //qDebug() << "Received arguments" << argsValue; /*Q_FOREACH(QJsonValue val, argsArray) { arguments << val.toVariant(); }*/ } else { qDebug() << "Args argument is not an array"; return; } } Q_EMIT(eventReceived(message, arguments)); } else { qDebug() << "Invalid event received: no name"; } } } break; } case 6: //ack { QRegExp regExp("^([0-9]+)(\\+)?(.*)$", Qt::CaseInsensitive, QRegExp::RegExp2); if (regExp.indexIn(data) != -1) { QJsonParseError parseError; //QVariantList arguments; QJsonArray arguments; int messageId = regExp.cap(1).toInt(); QString argumentsValue = regExp.cap(3); if (!argumentsValue.isEmpty()) { QJsonDocument doc = QJsonDocument::fromJson(argumentsValue.toLatin1(), &parseError); if (parseError.error != QJsonParseError::NoError) { qDebug() << "JSONParseError:" << parseError.errorString(); return; } else { if (doc.isArray()) { //arguments = doc.array().toVariantList(); arguments = doc.array(); } else { qDebug() << "Error: data of event is not an array"; return; } } } Q_EMIT(ackReceived(messageId, arguments)); } break; } case 7: //error { QStringList pieces = data.split("+"); QString reason = pieces[0]; QString advice; if (pieces.length() == 2) { advice = pieces[1]; } Q_EMIT(errorReceived(reason, advice)); break; } case 8: //noop { qDebug() << "Noop received" << data; break; } } } }
void JsonDbReduceDefinition::updateObject(JsonDbObject before, JsonDbObject after, JsonDbUpdateList *changeList) { initScriptEngine(); QJsonValue beforeKeyValue = sourceKeyValue(before); QJsonValue afterKeyValue = sourceKeyValue(after); if (jsondbSettings->debug()) qDebug() << "JsonDbReduceDefinition::updateObject" << "beforeKeyValue" << beforeKeyValue << "afterKeyValue" << afterKeyValue; if (!after.isEmpty() && !after.isDeleted() && !before.isEmpty() && (beforeKeyValue != afterKeyValue)) { // do a subtract only on the before key if (!beforeKeyValue.isUndefined()) updateObject(before, QJsonObject(), changeList); // and then continue here with the add with the after key before = QJsonObject(); } const QJsonValue keyValue((after.isEmpty() || after.isDeleted()) ? beforeKeyValue : afterKeyValue); if (keyValue.isUndefined()) return; GetObjectsResult getObjectResponse = mTargetTable->getObjects(mTargetKeyName, keyValue, mTargetType); if (!getObjectResponse.error.isNull()) setError(getObjectResponse.error.toString()); JsonDbObject previousObject; QJsonValue previousValue(QJsonValue::Undefined); JsonDbObjectList previousResults = getObjectResponse.data; for (int k = 0; k < previousResults.size(); ++k) { JsonDbObject previous = previousResults.at(k); if (previous.value(QStringLiteral("_reduceUuid")).toString() == mUuid) { previousObject = previous; previousValue = previousObject; break; } } QJsonValue value = previousValue; if (!before.isEmpty()) value = addObject(JsonDbReduceDefinition::Subtract, keyValue, value, before); if (!after.isEmpty() && !after.isDeleted()) value = addObject(JsonDbReduceDefinition::Add, keyValue, value, after); JsonDbObjectList objectsToUpdate; // if we had a previous object to reduce if (previousObject.contains(JsonDbString::kUuidStr)) { // and now the value is undefined if (value.isUndefined()) { // then remove it previousObject.markDeleted(); objectsToUpdate.append(previousObject); } else { //otherwise update it JsonDbObject reduced(value.toObject()); reduced.insert(JsonDbString::kTypeStr, mTargetType); reduced.insert(JsonDbString::kUuidStr, previousObject.value(JsonDbString::kUuidStr)); reduced.insert(JsonDbString::kVersionStr, previousObject.value(JsonDbString::kVersionStr)); reduced.insert(mTargetKeyName, keyValue); reduced.insert(QStringLiteral("_reduceUuid"), mUuid); objectsToUpdate.append(reduced); } } else if (!value.isUndefined()) { // otherwise create the new object JsonDbObject reduced(value.toObject()); reduced.insert(JsonDbString::kTypeStr, mTargetType); reduced.insert(mTargetKeyName, keyValue); reduced.insert(QStringLiteral("_reduceUuid"), mUuid); objectsToUpdate.append(reduced); } JsonDbWriteResult res = mPartition->updateObjects(mOwner, objectsToUpdate, JsonDbPartition::ViewObject, changeList); if (res.code != JsonDbError::NoError) setError(QString::fromLatin1("Error executing add function: %1").arg(res.message)); }
QColor Serializer::toColor(const QJsonValue& array) { QJsonArray a = array.toArray(); return QColor(a[0].toInt(), a[1].toInt(), a[2].toInt()); }
static bool matches(const QJsonObject &object, const QString &osName, const QVersionNumber &kernelVersion, const QOpenGLConfig::Gpu &gpu) { const OsTypeTerm os = OsTypeTerm::fromJson(object.value(osKey())); if (!os.isNull() && !os.matches(osName, kernelVersion)) return false; const QJsonValue exceptionsV = object.value(exceptionsKey()); if (exceptionsV.isArray()) { const QJsonArray exceptionsA = exceptionsV.toArray(); for (JsonArrayConstIt it = exceptionsA.constBegin(), cend = exceptionsA.constEnd(); it != cend; ++it) { if (matches(it->toObject(), osName, kernelVersion, gpu)) return false; } } const QJsonValue vendorV = object.value(vendorIdKey()); if (vendorV.isString()) { if (gpu.vendorId != vendorV.toString().toUInt(Q_NULLPTR, /* base */ 0)) return false; } else { if (object.contains(glVendorKey())) { const QByteArray glVendorV = object.value(glVendorKey()).toString().toUtf8(); if (!gpu.glVendor.contains(glVendorV)) return false; } } if (gpu.deviceId) { const QJsonValue deviceIdV = object.value(deviceIdKey()); switch (deviceIdV.type()) { case QJsonValue::Array: if (!contains(deviceIdV.toArray(), gpu.deviceId)) return false; break; case QJsonValue::Undefined: case QJsonValue::Null: break; default: qWarning().noquote() << msgSyntaxWarning(object, QLatin1String("Device ID must be of type array.")); } } if (!gpu.driverVersion.isNull()) { const QJsonValue driverVersionV = object.value(driverVersionKey()); switch (driverVersionV.type()) { case QJsonValue::Object: if (!VersionTerm::fromJson(driverVersionV).matches(gpu.driverVersion)) return false; break; case QJsonValue::Undefined: case QJsonValue::Null: break; default: qWarning().noquote() << msgSyntaxWarning(object, QLatin1String("Driver version must be of type object.")); } } return true; }
void MessageBoxType4::init(const QJsonValue &value) { QPalette pal; pal.setColor(QPalette::Background, Qt::white); QFont nameFont; nameFont.setBold(true); QString offsetStyleSheet = "margin-left: " + QString::number(MessageBoxType4::commentOffset) + ";"; userName = new QLabel(this); userName->setFont(nameFont); userName->setStyleSheet(offsetStyleSheet + "color: gray;"); memberText = new QLabel(this); memberText->setAutoFillBackground(true); memberText->setPalette(pal); commentText = new QLabel(this); commentText->setAutoFillBackground(true); //commentText->setPalette(pal); commentText->setStyleSheet(offsetStyleSheet + "background-color: white;" "color: gray"); if(parentWidget() != NULL) { memberText->setFixedWidth(parentWidget()->width() - 40); commentText->setFixedWidth(parentWidget()->width() - 40 - MessageBoxType4::commentOffset); } QJsonObject post = value.toObject()["posts"].toArray()[0].toObject(); QJsonArray postBody = post["body"].toArray(); QString text = ""; QString comment = ""; for(int i = 0; i < postBody.count(); i++) { QJsonObject obj = postBody[i].toObject(); int bodyType = obj["bodyType"].toInt(); if(bodyType == 1) text += obj["text"].toString(); else if(bodyType == 4) { QJsonObject commentJson = obj["comment"] .toObject(); userName->setText(commentJson["sendUserName"].toString()); commentText->setText(commentJson["text"].toString()); commentText->setWordWrap(true); commentText->setMinimumHeight(commentText->sizeHint().height()); } } memberText->setText(text); memberText->setWordWrap(true); memberText->setMinimumHeight(memberText->sizeHint().height()); layout->addWidget(memberText, 1, 0); layout->addWidget(userName, 2, 0); layout->addWidget(commentText, 3, 0); QTimer *timer = new QTimer; QObject::connect(timer, &QTimer::timeout, [=] { timer->stop(); timer->deleteLater(); emit boxFinished(this); }); timer->start(100); }
void Client::activate(const QJsonValue& playerId){ if(playerId.toString() == Self->objectName()) setStatus(Playing); else setStatus(NotActive); }
bool ConfigParser::parseRov(QROV& rov) const { QByteArray fileContents = readFile(); if(fileContents.isEmpty()) return false; QJsonDocument configDoc(QJsonDocument::fromJson(fileContents)); QJsonObject baseObj = configDoc.object(); QJsonArray jsonSensors = baseObj["sensors"].toArray(); QJsonArray jsonRelays = baseObj["relays"].toArray(); QJsonArray jsonServos = baseObj["servos"].toArray(); QJsonValue jsonMotorLayout = baseObj["motorLayout"]; QJsonArray jsonMotorGears = baseObj["motorGears"].toArray(); QJsonValue jsonMaxDepth = baseObj["maxDepth"]; QJsonValue jsonGearIncButton = baseObj["gearIncButton"]; QJsonValue jsonGearDecButton = baseObj["gearDecButton"]; if(jsonSensors.size() == 0 || jsonRelays.size() == 0 || jsonServos.size() == 0 || jsonMotorLayout.isUndefined() || jsonMaxDepth.isUndefined()) return false; //TODO: READ IP VIDEO FEEDS? rov.relays.clear(); rov.servos.clear(); rov.sensors.clear(); rov.motors.clear(); rov.motorGears.clear(); for(int i=0; i<jsonRelays.count(); i++) { if(!jsonRelays[i].toObject().contains("name")) return false; rov.relays.append(QROVRelay(jsonRelays[i].toObject()["name"].toString(), false)); } for(int i=0; i<jsonServos.count(); i++) { if(!jsonServos[i].toObject().contains("name") || !jsonServos[i].toObject().contains("min") || !jsonServos[i].toObject().contains("max") || !jsonServos[i].toObject().contains("defaultValue")) return false; const int defVal = jsonServos[i].toObject()["defaultValue"].toInt(); rov.servos.append(QROVServo(jsonServos[i].toObject()["name"].toString(), defVal, jsonServos[i].toObject()["min"].toInt(), jsonServos[i].toObject()["max"].toInt(), defVal)); } for(int i=0; i<jsonSensors.count(); i++) { if(!jsonSensors[i].toObject().contains("units") || !jsonSensors[i].toObject().contains("name")) return false; rov.sensors.append(QROVSensor(jsonSensors[i].toObject()["name"].toString(), jsonSensors[i].toObject()["units"].toString(), 0)); } if(jsonMotorLayout.toString() == "vector") { rov.motorLayout = vectorDrive; for(int i=0; i<6; i++) { rov.motors.append(QROVMotor(1500)); } } else if(jsonMotorLayout.toString() == "tank") { rov.motorLayout = tankDrive; for(int i=0; i<3; i++) { rov.motors.append(QROVMotor(1500)); } } else { qWarning() << "Motor layout: " << jsonMotorLayout.toString() << " not defined!"; return false; } rov.motorGears.append(0); // in this gear, disable the ROV for(int i=0; i<jsonMotorGears.count(); i++) { rov.motorGears.append(jsonMotorGears[i].toDouble()); } if(rov.motorGears.length() < 1) { rov.motorGears.append(1.0); } rov.maxDepth = jsonMaxDepth.toDouble(100); rov.gearIncButton = jsonGearIncButton.toInt(0); rov.gearDecButton = jsonGearDecButton.toInt(0); return true; }
void Client::jilei(const QJsonValue &jilei_str){ Self->jilei(jilei_str.toString()); }
bool TestClusterModel::loadFromFile(const QString& fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return false; } QByteArray bytes = file.readAll(); file.close(); QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseError); if (parseError.error != QJsonParseError::NoError) { return false; } if (!doc.isArray()) { return false; } QList<HostInfo> newHosts; QJsonArray array = doc.array(); for (const QJsonValue& value : array) { HostInfo info; QJsonObject object = value.toObject(); QJsonValue typeVal = object["type"]; if (!typeVal.isString()) { return false; } int type = findHostTypeByInternalName(typeVal.toString().toUtf8().data()); if (type < 0) { return false; } info.type = (HostType)type; QJsonValue portVal = object["port"]; if (!portVal.isDouble()) { return false; } info.port = static_cast<int>(portVal.toDouble()); QJsonValue dbPathVal = object["dbPath"]; if (dbPathVal.isString()) { info.dbPath = dbPathVal.toString(); } QJsonValue replicaSetVal = object["replicaSet"]; if (replicaSetVal.isString()) { info.replicaSet = replicaSetVal.toString(); } QJsonValue configDBVal = object["configDB"]; if (configDBVal.isString()) { info.configDB = configDBVal.toString(); } newHosts.append(info); } for (HostInfo& info : newHosts) { info.process = new QProcess(this); info.state = QProcess::NotRunning; } beginInsertRows(QModelIndex(), 0, newHosts.size() - 1); _hosts = newHosts; endInsertRows(); _fileName = fileName; _dirty = false; return true; }
void Client::judgeResult(const QJsonValue &result_str){ QJsonArray texts = result_str.toArray(); QString who = texts.at(0).toString(); bool is_good = texts.at(1).toBool(); emit judge_result(who, is_good); }
void NgfpReader::attrFromJson (const QJsonValue &j_attr, Attr *attr) { AttrInputType input_type = attr->getInputType(); QVariant var; if (input_type == AttrInputType::Boolean) { var = j_attr.toBool(); } else if (input_type == AttrInputType::Number) { var = j_attr.toInt(); } else if (input_type == AttrInputType::String) { var = j_attr.toString(); } else if (input_type == AttrInputType::StringList || input_type == AttrInputType::PageList) { QStringList list; QJsonArray j_arr = j_attr.toArray(QJsonArray()); for (int i = 0; i < j_arr.size(); i++) list.append(j_arr[i].toString()); var = list; } else if (input_type == AttrInputType::DateTime) { var = QDateTime::fromString(j_attr.toString(), FB_NGFP_DATETIME_FORMAT_DT); } else if (input_type == AttrInputType::Enum) { var = j_attr.toInt(); } else if (input_type == AttrInputType::DoubleItems) { DoubleItemsValue value; QJsonArray j_arr = j_attr.toArray(QJsonArray()); value.def_index = -1; for (int i = 0; i < j_arr.size(); i++) { QJsonValue j_arr_item = j_arr[i]; value.inners.append(j_arr_item.toObject()["name"].toString()); value.outers.append(j_arr_item.toObject()["alias"].toString()); if (!j_arr_item.toObject().value("default").isUndefined()) value.def_index = i; } var = QVariant::fromValue<DoubleItemsValue>(value); } else if (input_type == AttrInputType::TripleItems) { TripleItemsValue value; QJsonArray j_arr = j_attr.toArray(QJsonArray()); value.def_index = -1; for (int i = 0; i < j_arr.size(); i++) { QJsonValue j_arr_item = j_arr[i]; value.inners.append(j_arr_item.toObject()["name"].toString()); value.outers_left.append(j_arr_item.toObject()["alias"].toString()); value.outers_right.append(j_arr_item.toObject()["alias2"].toString()); if (!j_arr_item.toObject().value("default").isUndefined()) value.def_index = i; } var = QVariant::fromValue<TripleItemsValue>(value); } else if (input_type == AttrInputType::DepDoubleItems) { DepDoubleItemsValue value; QJsonArray j_arr = j_attr.toArray(QJsonArray()); value.main.def_index = -1; for (int i = 0; i < j_arr.size(); i++) { QJsonValue j_arr_item = j_arr[i]; value.main.inners.append(j_arr_item.toObject()["name"].toString()); value.main.outers.append(j_arr_item.toObject()["alias"].toString()); if (!j_arr_item.toObject().value("default").isUndefined()) value.main.def_index = i; value.deps.append(DoubleItemsValue()); QJsonValue j_arr2_val = j_arr_item.toObject()["values"]; QJsonArray j_arr2 = j_arr2_val.toArray(QJsonArray()); if (!(j_arr2.size() == 1 && j_arr2[0].toObject()["name"].toString() == "-1" && j_arr2[0].toObject()["alias"].toString() == "--")) { value.deps.last().def_index = -1; for (int i2 = 0; i2 < j_arr2.size(); i2++) { QJsonValue j_arr_item2 = j_arr2[i2]; value.deps.last().inners.append(j_arr_item2.toObject()["name"].toString()); value.deps.last().outers.append(j_arr_item2.toObject()["alias"].toString()); if (!j_arr_item2.toObject().value("default").isUndefined()) value.deps.last().def_index = i2; } } } var = QVariant::fromValue<DepDoubleItemsValue>(value); } attr->setValueAsVar(var); }
void AppModel::handleForecastNetworkData(QObject *replyObj) { qCDebug(requestsLog) << "got forecast"; QNetworkReply *networkReply = qobject_cast<QNetworkReply*>(replyObj); if (!networkReply) return; if (!networkReply->error()) { QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); QJsonObject jo; QJsonValue jv; QJsonObject root = document.object(); jv = root.value(QStringLiteral("list")); if (!jv.isArray()) qWarning() << "Invalid forecast object"; QJsonArray ja = jv.toArray(); //we need 4 days of forecast -> first entry is today if (ja.count() != 5) qWarning() << "Invalid forecast object"; QString data; for (int i = 1; i<ja.count(); i++) { WeatherData *forecastEntry = new WeatherData(); //min/max temperature QJsonObject subtree = ja.at(i).toObject(); jo = subtree.value(QStringLiteral("temp")).toObject(); jv = jo.value(QStringLiteral("min")); data.clear(); data += niceTemperatureString(jv.toDouble()); data += QChar('/'); jv = jo.value(QStringLiteral("max")); data += niceTemperatureString(jv.toDouble()); forecastEntry->setTemperature(data); //get date jv = subtree.value(QStringLiteral("dt")); QDateTime dt = QDateTime::fromMSecsSinceEpoch((qint64)jv.toDouble()*1000); forecastEntry->setDayOfWeek(dt.date().toString(QStringLiteral("ddd"))); //get icon QJsonArray weatherArray = subtree.value(QStringLiteral("weather")).toArray(); jo = weatherArray.at(0).toObject(); forecastEntry->setWeatherIcon(jo.value(QStringLiteral("icon")).toString()); //get description forecastEntry->setWeatherDescription(jo.value(QStringLiteral("description")).toString()); d->forecast.append(forecastEntry); } if (!(d->ready)) { d->ready = true; emit readyChanged(); } emit weatherChanged(); } networkReply->deleteLater(); }
// Some magic required by .ngfp format. void NgfpReader::modifySpecificElemView (const QJsonValue &j_elemview, ElemView *elemview, Project *project, Screen *screen) { auto modifyTabs = [&]() { auto attrs = elemview->getElem()->getAttrs(); QJsonArray j_pages = j_elemview.toObject()["pages"].toArray(); TabsView *tabsview = qobject_cast<TabsView*>(elemview); if (tabsview == nullptr) return; int cur_page = 0; QStringList page_hdrs; tabsview->removeLastPage(); tabsview->removeLastPage(); for (int i = 0; i < j_pages.size(); i++) { page_hdrs.append(j_pages[i].toObject()["caption"].toString()); if (!j_pages[i].toObject().value("default").isUndefined()) cur_page = i; tabsview->appendPage(); containerFromJson(j_pages[i].toObject()["elements"].toArray(), tabsview->getAllContainers().last(), project, screen); // recursion } Attr* attr_page_hdrs = attrs.value("page_hdrs"); attr_page_hdrs->setValueAsVar(page_hdrs); tabsview->headers = page_hdrs; Attr* attr_cur_page = attrs.value("cur_page"); static_cast<Number*>(attr_cur_page)->setMax(page_hdrs.size()); static_cast<Number*>(attr_cur_page)->setValue(cur_page + 1); // because this attr values starts from 1 tabsview->cur_container_index = cur_page; }; auto modifyDateTimePicker = [&]() { auto attrs = elemview->getElem()->getAttrs(); QJsonObject j_attrs = j_elemview.toObject()["attributes"].toObject(); if (j_attrs["datetime"].isNull()) { attrs["date_is_cur"]->setValueAsVar(true); } else { attrs["date_is_cur"]->setValueAsVar(false); if (j_attrs["date_type"].toInt() == 0) attrs["init_date"]->setValueAsVar(QDateTime::fromString(j_attrs["datetime"].toString(), FB_NGFP_DATETIME_FORMAT_D)); else if (j_attrs["date_type"].toInt() == 1) attrs["init_date"]->setValueAsVar(QDateTime::fromString(j_attrs["datetime"].toString(), FB_NGFP_DATETIME_FORMAT_T)); else attrs["init_date"]->setValueAsVar(QDateTime::fromString(j_attrs["datetime"].toString(), FB_NGFP_DATETIME_FORMAT_DT)); } }; auto modifyComboBox = [&]() { // nothing to do here for reading }; auto modifyCounter = [&]() { // nothing to do here for reading }; auto modifyTextEdit = [&]() { // nothing to do here for reading }; if (!j_elemview.isObject()) return; if (elemview == nullptr) return; typedef std::function<void()> ModifierCallback; const QString &elem_name = elemview->getKeyName(); const QMap<QString, ModifierCallback> modifiers = { {{"tabs"}, {modifyTabs}}, {{"datetimepicker"}, {modifyDateTimePicker}}, {{"combobox"}, {modifyComboBox}}, {{"counter"}, {modifyCounter}}, {{"textedit"}, {modifyTextEdit}} }; if (!modifiers.contains(elem_name)) return; modifiers.value(elem_name)(); // call function }
void protoObject::fromJSON(QJsonObject &obj) { //TODO: internal id check //qDebug() << obj; QMap<QString, QMap<int, protoObject* >* > bufferMap; QMap<int, protoObject* >* tmp_bufferMap; int length = obj.size(); int i; protoObject* tmp_obj; QStringList keys = obj.keys(); QJsonValue value; QJsonObject json_obj; QJsonObject json_info; for (i = 0; i < length; i++) { value = obj.value(keys.at(i)); if (value.isArray()) { QJsonArray tmp_arr = value.toArray(); QList< QSharedPointer<protoObject> > list; int length = tmp_arr.count(), j; for (j = 0; j < length; j++) { tmp_obj = new protoObject(this); value = tmp_arr.at(j); if (value.isObject()) { json_obj = value.toObject(); tmp_obj->fromJSON(json_obj); }; list.append(QSharedPointer<protoObject >(tmp_obj)); }; qDebug() << list; this->setProperty(keys.at(i).toLatin1(), QVariant::fromValue(list)); }; if (value.isObject()) { tmp_obj = new protoObject(this); json_obj = value.toObject(); tmp_obj->fromJSON(json_obj); QVariant variant = QVariant::fromValue(QSharedPointer<protoObject>(tmp_obj)); this->setProperty(keys.at(i).toLatin1(), variant); }; if (value.isString()) this->setProperty(keys.at(i).toLatin1(), value.toString()); if (value.isDouble()) this->setProperty(keys.at(i).toLatin1(), value.toDouble()); if (value.isBool()) this->setProperty(keys.at(i).toLatin1(), value.toBool()); }; }
v8::Handle<v8::Value> QV8JsonWrapper::fromJsonValue(const QJsonValue &value) { if (value.isString()) return QJSConverter::toString(value.toString()); else if (value.isDouble()) return v8::Number::New(value.toDouble()); else if (value.isBool()) return value.toBool() ? v8::True() : v8::False(); else if (value.isArray()) return fromJsonArray(value.toArray()); else if (value.isObject()) return fromJsonObject(value.toObject()); else if (value.isNull()) return v8::Null(); else return v8::Undefined(); }
static Nuria::JsonMetaObjectReader::Error parseTypeObject (const QByteArray &typeName, const QJsonObject &type, Nuria::MetaObjectMap &objects) { using namespace Nuria; QJsonValue annotationsValue = type.value (QStringLiteral("annotations")); QJsonValue basesValue = type.value (QStringLiteral("bases")); QJsonValue memberMethodsValue = type.value (QStringLiteral("memberMethods")); QJsonValue staticMethodsValue = type.value (QStringLiteral("staticMethods")); QJsonValue constructorsValue = type.value (QStringLiteral("constructors")); QJsonValue enumsValue = type.value (QStringLiteral("enums")); QJsonValue fieldsValue = type.value (QStringLiteral("fields")); // Type checks if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray; if (!basesValue.isArray ()) return JsonMetaObjectReader::BasesIsNotAnArray; if (!memberMethodsValue.isArray ()) return JsonMetaObjectReader::MemberMethodsIsNotAnArray; if (!staticMethodsValue.isArray ()) return JsonMetaObjectReader::StaticMethodsIsNotAnArray; if (!constructorsValue.isArray ()) return JsonMetaObjectReader::ConstructorsIsNotAnArray; if (!enumsValue.isObject ()) return JsonMetaObjectReader::EnumsIsNotAnObject; if (!fieldsValue.isObject ()) return JsonMetaObjectReader::FieldsIsNotAnObject; // Create meta object JsonMetaObjectReader::Error error; RuntimeMetaObject *metaObject = new RuntimeMetaObject (typeName); // Parse bases error = parseBasesArray (basesValue.toArray (), metaObject); if (error != Nuria::JsonMetaObjectReader::NoError) return error; // Parse annotations RuntimeMetaObject::AnnotationMap annotations; error = parseAnnotationsArray (annotationsValue.toArray (), annotations); if (error != Nuria::JsonMetaObjectReader::NoError) return error; // Parse methods JsonMetaObjectReader::Error errorMembers; JsonMetaObjectReader::Error errorStatics; JsonMetaObjectReader::Error errorCtors; errorMembers = parseMethodArray (MetaMethod::Method, memberMethodsValue.toArray (), metaObject); errorStatics = parseMethodArray (MetaMethod::Static, staticMethodsValue.toArray (), metaObject); errorCtors = parseMethodArray (MetaMethod::Constructor, constructorsValue.toArray (), metaObject); if (errorMembers != JsonMetaObjectReader::NoError) return errorMembers; if (errorStatics != JsonMetaObjectReader::NoError) return errorStatics; if (errorCtors != JsonMetaObjectReader::NoError) return errorCtors; // Parse enums error = parseEnumsObject (enumsValue.toObject (), metaObject); if (error != Nuria::JsonMetaObjectReader::NoError) return error; // Parse fields error = parseFieldsObject (fieldsValue.toObject (), metaObject); if (error != Nuria::JsonMetaObjectReader::NoError) return error; // Store and done. metaObject->setAnnotations (annotations); metaObject->finalize (); objects.insert (typeName, metaObject); return Nuria::JsonMetaObjectReader::NoError; }
AppInfo AppInfo::fromPath(const QString &path) { AppInfo info(Bundle::fromPath(path)); if (!static_cast<Bundle>(info).isValid()) { qCWarning(l) << "bundle" << path << "is not valid"; return AppInfo(); } QScopedPointer<QIODevice> appInfoJSON(info.openFile(AppInfo::INFO, QIODevice::Text)); if (!appInfoJSON) { qCWarning(l) << "cannot find app" << path << "info json"; return AppInfo(); } QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(appInfoJSON->readAll(), &parseError); if (parseError.error != QJsonParseError::NoError) { qCWarning(l) << "cannot parse app" << path << "info json" << parseError.errorString(); return AppInfo(); } appInfoJSON->close(); const QJsonObject root = doc.object(); info.d->uuid = QUuid(root["uuid"].toString()); info.d->shortName = root["shortName"].toString(); info.d->longName = root["longName"].toString(); info.d->companyName = root["companyName"].toString(); info.d->versionCode = root["versionCode"].toInt(); info.d->versionLabel = root["versionLabel"].toString(); const QJsonObject watchapp = root["watchapp"].toObject(); info.d->watchface = watchapp["watchface"].toBool(); info.d->jskit = info.fileExists(AppInfo::APPJS); if (root.contains("capabilities")) { const QJsonArray capabilities = root["capabilities"].toArray(); AppInfo::Capabilities caps = 0; for (auto it = capabilities.constBegin(); it != capabilities.constEnd(); ++it) { QString cap = (*it).toString(); if (cap == "location") caps |= AppInfo::Location; if (cap == "configurable") caps |= AppInfo::Configurable; } info.d->capabilities = caps; } if (root.contains("appKeys")) { const QJsonObject appkeys = root["appKeys"].toObject(); for (auto it = appkeys.constBegin(); it != appkeys.constEnd(); ++it) { info.addAppKey(it.key(), it.value().toInt()); } } if (root.contains("resources")) { const QJsonObject resources = root["resources"].toObject(); const QJsonArray media = resources["media"].toArray(); int index = 0; for (auto it = media.constBegin(); it != media.constEnd(); ++it) { const QJsonObject res = (*it).toObject(); const QJsonValue menuIcon = res["menuIcon"]; switch (menuIcon.type()) { case QJsonValue::Bool: info.d->menuIcon = menuIcon.toBool(); info.d->menuIconResource = index; break; case QJsonValue::String: info.d->menuIcon = !menuIcon.toString().isEmpty(); info.d->menuIconResource = index; break; default: break; } index++; } } if (info.uuid().isNull() || info.shortName().isEmpty()) { qCWarning(l) << "invalid or empty uuid/name in json of" << path; return AppInfo(); } return info; }