コード例 #1
0
ファイル: mainwindow.cpp プロジェクト: p1nkc0de/JSONExplorer
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;
}
コード例 #2
0
ファイル: qjsonvalue.cpp プロジェクト: venkatarajasekhar/Qt
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();
}
コード例 #3
0
static Nuria::JsonMetaObjectReader::Error parseFieldObject (const QString &name, const QJsonObject &field,
							    Nuria::RuntimeMetaObject *metaObject) {
	using namespace Nuria;
	
	QJsonValue annotationsValue = field.value (QStringLiteral("annotations"));
	QJsonValue readOnlyValue = field.value (QStringLiteral("readOnly"));
	QJsonValue typeValue = field.value (QStringLiteral("type"));
	
	// Type check
	if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray;
	if (!readOnlyValue.isBool ()) return JsonMetaObjectReader::FieldReadOnlyIsNotABoolean;
	if (!typeValue.isString ()) return JsonMetaObjectReader::FieldTypeIsNotAString;
	
	// Parse annotations
	JsonMetaObjectReader::Error error;
	
	RuntimeMetaObject::AnnotationMap annotations;
	error = parseAnnotationsArray (annotationsValue.toArray (), annotations);
	if (error != JsonMetaObjectReader::NoError) return error;
	
	// Store and done.
	QByteArray typeName = typeValue.toString ().toLatin1 ();
	
	if (readOnlyValue.toBool ()) {
		metaObject->addField (name.toLatin1 (), typeName, annotations, invalidGetter);
	} else {
		metaObject->addField (name.toLatin1 (), typeName, annotations, invalidGetter, invalidSetter);
	}
	
	return JsonMetaObjectReader::NoError;
}
コード例 #4
0
ファイル: jsonobject.cpp プロジェクト: lfritz/qtjsonhelper
bool JsonObject::boolean(const QString& key) const {
    checkContains(key);
    QJsonValue value = o.value(key);
    if ( ! value.isBool())
        wrongType("'true' or 'false'", key);
    return value.toBool();
}
コード例 #5
0
ファイル: yunclient.cpp プロジェクト: JinduYin/YQCMM
QJsonObject YunClient::getRequestData(QString array)
{
    QByteArray byte_array = array.toLocal8Bit();
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array, &json_error);

    QJsonObject dataJson;
    if(json_error.error == QJsonParseError::NoError)
    {
        if(!parse_doucment.isObject())
            return dataJson;

        QJsonObject json = parse_doucment.object();
        if(json.contains("status")){
            QJsonValue value = json.take("status");
            if(!value.toBool()){
                errView(json);
                return dataJson;
            }
        }

        if(json.contains("data")){
            dataJson = json.take("data").toObject();
        }
    }

    return dataJson;
}
コード例 #6
0
bool QJsonValueProto::toBool(bool defaultValue) const
{
  QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject());
  if (item)
    return item->toBool(defaultValue);
  return false;
}
コード例 #7
0
void DomainServerSettingsManager::recurseJSONObjectAndOverwriteSettings(const QJsonObject& postedObject,
                                                                        QVariantMap& settingsVariant,
                                                                        QJsonObject descriptionObject) {
    foreach(const QString& key, postedObject.keys()) {

        QJsonValue rootValue = postedObject[key];
        
        // we don't continue if this key is not present in our descriptionObject
        if (descriptionObject.contains(key)) {
            if (rootValue.isString()) {
                settingsVariant[key] = rootValue.toString();
            } else if (rootValue.isBool()) {
                settingsVariant[key] = rootValue.toBool();
            } else if (rootValue.isObject()) {
                // there's a JSON Object to explore, so attempt to recurse into it
                QJsonObject nextDescriptionObject = descriptionObject[key].toObject();
                
                if (nextDescriptionObject.contains(DESCRIPTION_SETTINGS_KEY)) {
                    if (!settingsVariant.contains(key)) {
                        // we don't have a map below this key yet, so set it up now
                        settingsVariant[key] = QVariantMap();
                    }
                    
                    recurseJSONObjectAndOverwriteSettings(rootValue.toObject(),
                                                          *reinterpret_cast<QVariantMap*>(settingsVariant[key].data()),
                                                          nextDescriptionObject[DESCRIPTION_SETTINGS_KEY].toObject());
                }
            }
        }
    }
}
コード例 #8
0
ファイル: etheripc.cpp プロジェクト: almindor/etherwall
    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();
    }
コード例 #9
0
DocumentFormattingProperty::DocumentFormattingProperty(const QJsonValue &value)
{
    if (value.isBool())
        *this = value.toBool();
    if (value.isDouble())
        *this = value.toDouble();
    if (value.isString())
        *this = value.toString();
}
コード例 #10
0
ファイル: etheripc.cpp プロジェクト: oktoshi/SOILsafe
    void EtherIPC::handleDeleteAccount() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            return bail();
        }

        const bool result = jv.toBool(false);
        emit deleteAccountDone(result, fActiveRequest.getIndex());
        done();
    }
コード例 #11
0
void Configuration::read(const QJsonObject &json)
{
    QJsonValue positionValue = json[KEY_POSITION];
    Utils::checkValue(KEY_POSITION, positionValue);
    QJsonObject jsonPosition = positionValue.toObject();

    QJsonValue positionXValue = jsonPosition[KEY_X];
    Utils::checkValue(KEY_X, positionXValue);
    positionX = positionXValue.toInt();

    QJsonValue positionYValue = jsonPosition[KEY_Y];
    Utils::checkValue(KEY_Y, positionYValue);
    positionY = positionYValue.toInt();

    QJsonValue scaleValue = json[KEY_SCALE];
    Utils::checkValue(KEY_SCALE, scaleValue);
    scale = scaleValue.toInt();

    QJsonValue fillValue = json[KEY_FILL];
    Utils::checkValue(KEY_FILL, fillValue);
    fill = fillValue.toBool();

    QJsonValue outlineValue = json[KEY_OUTLINE];
    Utils::checkValue(KEY_OUTLINE, outlineValue);
    outline = outlineValue.toBool();

    QJsonValue glyphsValue = json[KEY_GLYPHS];
    Utils::checkValue(KEY_GLYPHS, glyphsValue);
    if (!glyphsValue.isArray())
    {
        throw JsonParserException("""glyphs"" should be array");
    }
    QJsonArray figuresArray = glyphsValue.toArray();

    figure = new Figure();
    figure->read(figuresArray.first().toObject());

    panel = new Panel();
    panel->read(json);

}
コード例 #12
0
ファイル: mainwindow.cpp プロジェクト: p1nkc0de/JSONExplorer
void MainWindow::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    QJsonValue jsonObj = current->data(0, Qt::UserRole).toJsonValue();

    QJsonValue::Type jsonType = jsonObj.type();

    switch(jsonType)
    {
    case QJsonValue::Bool:
        ui->boolButton->setChecked(jsonObj.toBool());
        break;
    case QJsonValue::Double:
        ui->doubleValue->setValue(jsonObj.toDouble());
        break;
    case QJsonValue::String:
        ui->stringEdit->document()->setPlainText(jsonObj.toString());
        break;
    case QJsonValue::Array:
        {
            QJsonArray arr = jsonObj.toArray();
            int count = arr.count();

            ui->arrayList->clear();

            for(int i = 0; i < count; ++i)
            {
                QString label = renderJsonValue(arr.at(i));
                ui->arrayList->addItem(label);
            }
        }
        break;
    case QJsonValue::Object:
        {
            QJsonObject obj = jsonObj.toObject();
            ui->objectTable->setRowCount(obj.count());
            int row = 0;
            for(QJsonObject::ConstIterator i = obj.begin(); i != obj.end(); ++i, ++row)
            {
                QTableWidgetItem *keyItem = new QTableWidgetItem(i.key());
                QJsonValue val = i.value();
                QTableWidgetItem *valItem = new QTableWidgetItem(renderJsonValue(val));
                ui->objectTable->setItem(row, 0, keyItem);
                ui->objectTable->setItem(row, 1, valItem);
            }
        }
        break;
    default:
        break;
    }

    ui->typeSelector->setCurrentIndex(jsonObj.type() - 1);
}
コード例 #13
0
ファイル: switcherconfig.cpp プロジェクト: Ribtoks/xpiks
    bool tryGetBool(const QJsonObject &object, const QString &key, bool &value) {
        bool hasValue = false;

        if (object.contains(key)) {
            QJsonValue valueObject = object[key];
            if (valueObject.isBool()) {
                value = valueObject.toBool();
                hasValue = true;
            }
        }

        return hasValue;
    }
コード例 #14
0
QHash<QString, DocumentFormattingProperty> FormattingOptions::properties() const
{
    QHash<QString, DocumentFormattingProperty> ret;
    for (const QString &key : keys()) {
        if (key == tabSizeKey || key == insertSpaceKey)
            continue;
        QJsonValue property = value(key);
        if (property.isBool())
            ret[key] = property.toBool();
        if (property.isDouble())
            ret[key] = property.toDouble();
        if (property.isString())
            ret[key] = property.toString();
    }
    return ret;
}
コード例 #15
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();
}
コード例 #16
0
ファイル: etheripc.cpp プロジェクト: almindor/etherwall
    void EtherIPC::handleUnlockAccount() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            // special case, we def. need to remove all subrequests, but not stop timer
            fRequestQueue.clear();
            return bail(true);
        }

        const bool result = jv.toBool(false);

        if ( !result ) {
            setError("Unlock account failure");
            emit error();
        }
        emit unlockAccountDone(result, fActiveRequest.getIndex());
        done();
    }
コード例 #17
0
ReturnedValue JsonObject::fromJsonValue(ExecutionEngine *engine, const QJsonValue &value)
{
    if (value.isString())
        return engine->currentContext()->d()->engine->newString(value.toString())->asReturnedValue();
    else if (value.isDouble())
        return Encode(value.toDouble());
    else if (value.isBool())
        return Encode(value.toBool());
    else if (value.isArray())
        return fromJsonArray(engine, value.toArray());
    else if (value.isObject())
        return fromJsonObject(engine, value.toObject());
    else if (value.isNull())
        return Encode::null();
    else
        return Encode::undefined();
}
コード例 #18
0
ファイル: WebServer.cpp プロジェクト: draringi/pcbsd
QString WebServer::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;
}
コード例 #19
0
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;
    }
}
コード例 #20
0
ファイル: etheripc.cpp プロジェクト: oktoshi/SOILsafe
    void EtherIPC::handleUnlockAccount() {
        QJsonValue jv;
        if ( !readReply(jv) ) {
            return bail();
        }

        const bool result = jv.toBool(false);

        if ( !result ) {
            setError("Unlock account failure");
            if ( parseVersionNum() == 100002 ) {
                fError += " Gsoil v1.0.2 has a bug with unlocking empty password accounts! Consider updating";
            }
            emit error();
        }
        emit unlockAccountDone(result, fActiveRequest.getIndex());
        done();
    }
コード例 #21
0
ファイル: protoobject.cpp プロジェクト: jcapoduri/ndlite
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());
    };
}
コード例 #22
0
ファイル: yunclient.cpp プロジェクト: JinduYin/YQCMM
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);
}
コード例 #23
0
bool LedRun::fromJson(QJsonObject& obj) {
    QJsonValue dmxStartValue = obj.value("start");
    QJsonValue dmxEndValue = obj.value("end");
    QJsonValue reverseValue = obj.value("reverse");

    if(dmxStartValue.isUndefined() || dmxEndValue.isUndefined()){

        qCritical() << "Missing DMX start or end address";

        return false;
    }

    bool parseSuccess = true;

    QJsonObject dmxStartObj = dmxStartValue.toObject();
    QJsonObject dmxEndObj = dmxEndValue.toObject();

    parseSuccess &= dmxStart.fromJson( dmxStartObj );
    parseSuccess &= dmxEnd.fromJson( dmxEndObj );
    reverse = reverseValue.toBool();

    return parseSuccess;
}
コード例 #24
0
ファイル: ngfp_reader.cpp プロジェクト: nextgis/formbuilder
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);
}
コード例 #25
0
void FayeConnector::message(QString text)
{
  QJsonParseError err;
  QJsonDocument message = QJsonDocument::fromJson(text.toUtf8(), &err);

  if (err.error != QJsonParseError::NoError)
  {
    qDebug() << "Error parsing JSon " << err.error;
    emit error(err.error);
    return;
  }

  QJsonObject obj;
  if (message.isArray())
  {
    QJsonArray array = message.array();
    QJsonValue val = array.first();
    obj = val.toObject();
  }
  else
    obj = message.object();

  switch(status)
  {
     case CONNECTING:
     {
          QJsonValue successful = obj.value("successful");
          if (successful.toBool())
          {
            clientId = obj.value("clientId").toString();
            status = CONNECTED;
            emit statusChanged(CONNECTED);
          }
          else
            qDebug() << "Something is wrong: " << text;
     }
     break;
     case SUBSCRIBING:
     {
          QJsonValue successful = obj.value("successful");
          if (successful.toBool())
          {
            status = SUBSCRIBED;
            emit statusChanged(SUBSCRIBED);
            this->keepAlive();
          }
          else
            qDebug() << "Something is wrong: " << text;
     }
     break;
     case SUBSCRIBED:
     {
        if (obj.value("channel").toString().contains("/meta/connect", Qt::CaseInsensitive))
        {
            QJsonValue successful = obj.value("successful");
            if (successful.toBool())
              this->keepAlive();
            else
              qDebug() << "Something is wrong: " << text;
        }
        else
        {
            //qDebug() << text;
            emit messageReceived(text);
        }
     }
     break;
     default:
        //do nothing
     break;
   }
}
コード例 #26
0
ファイル: AssetsUtils.cpp プロジェクト: ACGaming/MultiMC5
/*
 * Returns true on success, with index populated
 * index is undefined otherwise
 */
bool loadAssetsIndexJson(QString path, AssetsIndex *index)
{
	/*
	{
	  "objects": {
		"icons/icon_16x16.png": {
		  "hash": "bdf48ef6b5d0d23bbb02e17d04865216179f510a",
		  "size": 3665
		},
		...
		}
	  }
	}
	*/

	QFile file(path);

	// Try to open the file and fail if we can't.
	// TODO: We should probably report this error to the user.
	if (!file.open(QIODevice::ReadOnly))
	{
		QLOG_ERROR() << "Failed to read assets index file" << path;
		return false;
	}

	// Read the file and close it.
	QByteArray jsonData = file.readAll();
	file.close();

	QJsonParseError parseError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &parseError);

	// Fail if the JSON is invalid.
	if (parseError.error != QJsonParseError::NoError)
	{
		QLOG_ERROR() << "Failed to parse assets index file:" << parseError.errorString()
					 << "at offset " << QString::number(parseError.offset);
		return false;
	}

	// Make sure the root is an object.
	if (!jsonDoc.isObject())
	{
		QLOG_ERROR() << "Invalid assets index JSON: Root should be an array.";
		return false;
	}

	QJsonObject root = jsonDoc.object();

	QJsonValue isVirtual = root.value("virtual");
	if (!isVirtual.isUndefined())
	{
		index->isVirtual = isVirtual.toBool(false);
	}

	QJsonValue objects = root.value("objects");
	QVariantMap map = objects.toVariant().toMap();

	for (QVariantMap::const_iterator iter = map.begin(); iter != map.end(); ++iter)
	{
		// QLOG_DEBUG() << iter.key();

		QVariant variant = iter.value();
		QVariantMap nested_objects = variant.toMap();

		AssetObject object;

		for (QVariantMap::const_iterator nested_iter = nested_objects.begin();
			 nested_iter != nested_objects.end(); ++nested_iter)
		{
			// QLOG_DEBUG() << nested_iter.key() << nested_iter.value().toString();
			QString key = nested_iter.key();
			QVariant value = nested_iter.value();

			if (key == "hash")
			{
				object.hash = value.toString();
			}
			else if (key == "size")
			{
				object.size = value.toDouble();
			}
		}

		index->objects.insert(iter.key(), object);
	}

	return true;
}
コード例 #27
0
void MixerControllerImpl::pr_getMute(const QJsonValue &response)
{
    emit getMuteReceived(response.toBool());
}
コード例 #28
0
ファイル: QJsonDocument.cpp プロジェクト: Iv/FlyHigh
//------------------------------------------------------------------------------
// 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;
}
コード例 #29
0
void MixerControllerImpl::pr_setVolume(const QJsonValue &response)
{
    emit setVolumeReceived(response.toBool());
}
コード例 #30
0
ファイル: appinfo.cpp プロジェクト: 0312birdzhang/pebble
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;
}