예제 #1
0
// === GENERAL PURPOSE UTILITY FUNCTIONS ===
QString WebSocket::JsonValueToString(QJsonValue val){
  //Note: Do not use this on arrays - only use this on single-value values
  QString out;
  switch(val.type()){
    case QJsonValue::Bool:
	out = (val.toBool() ? "true": "false"); break;
    case QJsonValue::Double:
	out = QString::number(val.toDouble()); break;
    case QJsonValue::String:
	out = val.toString(); break;
    case QJsonValue::Array:
	out = "\""+JsonArrayToStringList(val.toArray()).join("\" \"")+"\"";
    default:
	out.clear();
  }
  return out;
}
예제 #2
0
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();
}
QString jsonParser::valueToString(QJsonValue value, QString defaultValue)
{
    switch (value.type())
    {
    case QJsonValue::Bool:
        if (value.toBool() == true)
            return "true";
        else return "false";
        break;
    case QJsonValue::Double:
        return QString::number(value.toDouble());
        break;
    case QJsonValue::String:
        return value.toString(defaultValue);
    default:
        return defaultValue;
    }
}
예제 #4
0
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());
    };
}
예제 #5
0
파일: shadow.cpp 프로젝트: garfeng/shadow
QString Shadow::GetJsonVal(QString key,QJsonObject jsonObj)
{
    if(jsonObj.contains(key))
    {
        QJsonValue value = jsonObj.take(key);
        if(value.isDouble())
        {
            int valueInt = (int)(value.toDouble());
            QString str = QString::number(valueInt);
            return str;
        } else if(value.isString()){
            QString valueString = value.toString();
            return valueString;
        } else {
            return "";
        }
    }
    return "";
}
예제 #6
0
void YunClient::setVersionList(QJsonArray json)
{
    rowList.clear();
    for (int i=0; i<json.size(); i++)
    {
        QJsonObject vjson = json.at(i).toObject();
        QStringList rowValue;

        rowValue.append(QString::number(i+1));
        if(vjson.contains("versionId")){
            QJsonValue value = vjson.take("versionId");
            rowValue.append(QString::number(value.toInt()));
        }
        if(vjson.contains("versionName")){
            QJsonValue value = vjson.take("versionName");
            rowValue.append(value.toString());
        }
        if(vjson.contains("versionSize")){
            QJsonValue value = vjson.take("versionSize");
            rowValue.append(QString::number(value.toDouble()));
        }
        if(vjson.contains("versionInfo")){
            QJsonValue value = vjson.take("versionInfo");
            rowValue.append(value.toString());
        }
        if(vjson.contains("releaseTime")){
            QJsonValue value = vjson.take("releaseTime");
            rowValue.append(value.toString());
        }
        if(vjson.contains("isUpdate")){
            QJsonValue value = vjson.take("isUpdate");
            QString status("未更新");
            if (value.toBool())
                status = "已更新";
            rowValue.append(status);
        }

        rowList.append(rowValue);
    }

    update_list->setModelValue(rowList);
}
예제 #7
0
QVariant JsonTablemodel::data(const QModelIndex &index, int role) const
{
	if (index.row() >= mData.count() || index.column() >= mMapping.count())
	{
		return QVariant();
	}

	if (role == Qt::DisplayRole || role == Qt::EditRole)
	{
		QJsonObject object = mData.at(index.row());
		QString name = mMapping.at(index.column());
        QJsonValue value = object[name];
        if (value.isDouble())
        {
            return QString("$") + QString::number(value.toDouble());
        }
        return value.toVariant();
	}
	return QVariant();
}
예제 #8
0
bool Filter::parseSingleFloatParameter(const QJsonValue& parameters, const QString& name, float& output) {
    if (parameters.isDouble()) {
        output = parameters.toDouble();
        return true;
    } else if (parameters.isArray()) {
        auto arrayParameters = parameters.toArray();
        if (arrayParameters.size() > 1) {
            output = arrayParameters[0].toDouble();
            return true;
        }
    } else if (parameters.isObject()) {
        static const QString JSON_MIN = QStringLiteral("interval");
        auto objectParameters = parameters.toObject();
        if (objectParameters.contains(name)) {
            output = objectParameters[name].toDouble();
            return true;
        }
    } 
    return false;
}
예제 #9
0
QVariant ConversionUtil::fromJsonValue(QVariant::Type type, int userType, const QJsonValue &value) {

    switch (type) {
        case QVariant::Bool:
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::Double:
        case QVariant::String:
        case QVariant::Map:
            return value.toVariant();
        case QVariant::StringList: {
            QStringList stringList;
            for (const QJsonValue &item : value.toArray()) {
                stringList.append(item.toString());
            }
            return stringList;
        }
        case QVariant::DateTime:
            return QDateTime::fromMSecsSinceEpoch((qint64) value.toDouble());
        case QVariant::UserType: {
            MetaTypeRegistry::JsonConverters converters =
                    MetaTypeRegistry::jsonConverters(QMetaType::typeName(userType));
            if (converters.jsonValueToTypeConverter) {
                return converters.jsonValueToTypeConverter(value);
            } else {
                const char *typeName = QMetaType::typeName(userType);
                throw GameException(GameException::SerializationException, typeName ?
                                    QStringLiteral("User type not serializable: %1").arg(typeName) :
                                    QStringLiteral("Unknown user type: %1").arg(userType));
            }
        }
        default:
            throw GameException(GameException::SerializationException,
                                QStringLiteral("Unknown type: %1").arg(QVariant::typeToName(type)));
    }
}
예제 #10
0
/**
 * DBInterface::jsonToDataBufferVector
 * @brief iterate through JSON and return data inside json_ as vector of DataBuffer
 * @param json_ JSON string to convert
 * @return returns a vector of DataBuffer which contains the data inside json_
 *
 * This function can convert a json received from either InfluxDB or TODO
 * to a vector of DataBuffers.
 * If the JSONs origin was InfluxDB, the return values contains a DataBuffer for
 * every DateTime which was requested from InfluxDB.
 */
vector<DataBuffer> DBInterface::jsonToDataBufferVector(const string &json_, const string& dataSource_) {
    vector<DataBuffer> result;
    QString jsonQString(json_.c_str());
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonQString.toUtf8());
    QJsonObject jsonObject = jsonDocument.object();

    // parse json from influxdb
    if (jsonObject.contains(QString("results"))) {
        QJsonArray tempArray = jsonObject["results"].toArray();
        QJsonObject tempObject = tempArray.first().toObject();
        if (tempObject.contains(QString("series"))) {
            tempArray = tempObject["series"].toArray();
            tempObject = tempArray.first().toObject();
            if (tempObject.contains(QString("columns")) &&
                tempObject.contains(QString("values" )) ){
                QJsonArray names  = tempObject["columns"].toArray();
                QJsonArray values = tempObject["values" ].toArray();

                // iterate through all datasets
                typedef QJsonArray::iterator it_type;
                for(it_type iterator = values.begin(); iterator != values.end(); iterator++) {
                    QJsonArray dataSet = values.at(iterator.i).toArray();
                    DataBuffer tempDataBuffer;
                    // iterate to all names/values in a dataset
                    for(it_type iterator2 = dataSet.begin(); iterator2 != dataSet.end(); iterator2++) {

                        // get name
                        string name = names.at(iterator2.i).toString().toStdString();
                        // get value
                        QJsonValue valueJSON = dataSet.at(iterator2.i);

                        // set time
                        if (name == "time") {
                            struct tm time = stringToCTime(valueJSON.toString().toStdString());
                            tempDataBuffer.useDateTimes = true;
                            tempDataBuffer.startDateTime = time;
                            tempDataBuffer.endDateTime   = time;
                        } else {
                            // set values
                            double valueDouble = valueJSON.toDouble();
                            tempDataBuffer.data[name] = cutValueToInfluxDBRange(valueDouble);
                        }
                    }
                    // add DataSource;
                    tempDataBuffer.useDataSource = true;
                    tempDataBuffer.dataSource = cleanString(dataSource_);

                    // add data buffer to vector
                    result.push_back(tempDataBuffer);

                }
            } else {
                log << SLevel(ERROR) << "Aborted parsing InfluxDB-Json to databuffer. Unable to find 'columns and/or 'values' in JSON" << endl;
            }
        } else {
            log << SLevel(ERROR) << "Aborted parsing InfluxDB-Json to databuffer. Unable to find 'series' in JSON" << endl;
        }
    }


    return result;
}
예제 #11
0
vec3 vec3FromJsonValue(const QJsonValue& v) {
    if (v.isDouble()) {
        return vec3((float)v.toDouble());
    }
    return glmFromJson<vec3>(v);
}
예제 #12
0
BTCETrade::BTCETrade(const QJsonValue &amount, const QJsonValue &date,
                     const QJsonValue &price, const QJsonValue &tid,
                     const QJsonValue &tradeType)
    : amount_(amount.toDouble()), date_(date.toInt()), price_(price.toDouble()),
      tid_(tid.toInt()), tradeType_(tradeType.toString())
{}
BlockOptionType BlockOptionType_fromJson(QJsonValue node, bool *ok) {
    *ok = node.isDouble() && (node.toDouble() == node.toInt());
    return (BlockOptionType)(node.toInt());
}
예제 #14
0
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;
}
예제 #15
0
void Client::setPileNumber(const QJsonValue &pile_str){
	pile_num = pile_str.toDouble();

	updatePileNum();
}
예제 #16
0
//------------------------------------------------------------------------------
// 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;
}
예제 #17
0
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();
}