jsonqtqstringqlistqmap

Creating a QList of QMaps out of a QString


I'm having an struggle with a de-serializing operation, look I have a QString like this:

[{"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"}]

Ok, Now I want to make a QList of QMap s out of the string above. that simple but confusing, do I have to parse my string by hand? or is there any code or tool that can do it for me with no charge? :))


Solution

  • That looks like a JSON array, so you are in luck. Qt has JSON support so you can use that to parse it. Here is example code.

    #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;
    }