【问题标题】:Creating a QList of QMaps out of a QString从 QString 创建 QMap 的 QList
【发布时间】:2019-10-20 11:48:54
【问题描述】:

我在反序列化操作方面遇到了困难,看起来我有一个像这样的 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 qstring qlist qmap


【解决方案1】:

这看起来像一个 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;
}

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多