从 QString 创建 QMap 的 QList

Creating a QList of QMaps out of a QString

我在反序列化操作上遇到困难,看我有一个像这样的 QString:

[{"value": "", "type": "tag", "name": "Output Tag", "param": "outputtag"}, {"value": "black", "type": "colour", "name": "Init Colour", "param": "initcolour"}, {"value": "", "type": "colour", "name": "Off Colour", "param": "offcolour"}, {"value": "", "type": "colour", "name": "On Colour", "param": "oncolour"}]

好的,现在我想从上面的字符串中创建一个 QMap 的 QList。 这么简单但令人困惑,我必须手动解析我的字符串吗?还是有任何代码或工具可以免费为我做这件事? :))

这看起来像一个 JSON 数组,所以你很幸运。 Qt has JSON support 所以你可以用它来解析它。这是示例代码。

#include <QDebug>

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

#include <QList>
#include <QMap>

int main()
{
    // R"( is C++ raw string literal prefix
    QString inputString = R"(
[{"value": "", "type": "tag", "name": "Output Tag", "param": "outputtag"}, {"value": "black", "type": "colour", "name": "Init Colour", "param": "initcolour"}, {"value": "", "type": "colour", "name": "Off Colour", "param": "offcolour"}, {"value": "", "type": "colour", "name": "On Colour", "param": "oncolour"}]
)";

    QJsonParseError error;
    auto jsonDocument = QJsonDocument::fromJson(inputString.toUtf8(), &error);
    if (jsonDocument.isNull()) {
        qDebug() << "Parse error:" << error.errorString();
        return EXIT_FAILURE;
    }
    qDebug() << "Parsed QJsonDocument:\n" << jsonDocument;

    QList<QMap<QString, QString> > listOfMaps;

    if (!jsonDocument.isArray()) {
        qDebug() << "Invalid input, expecting array";
        return EXIT_FAILURE;
    }
    for(QJsonValue mapObject : jsonDocument.array()) {
        if(!mapObject.isObject()) {
            qDebug() << "Invalid input, expecting array of objects";
            return EXIT_FAILURE;
        }

        listOfMaps.append(QMap<QString, QString>{});
        for(QString key: mapObject.toObject().keys()) {
            listOfMaps.last().insert(key, mapObject[key].toString());
        }
    }

    qDebug() << "Resulting list of maps:\n" << listOfMaps;

    return EXIT_SUCCESS;
}