[Interest] QJsonDocument::fromVariant failing with list

Jérôme Godbout godboutj at amotus.ca
Tue Jun 8 22:42:52 CEST 2021


Most likely the QJson doesn’t known what to do with your QList<> type object. You should put those object into a QVariantList, right now you have a QVariantList that contain a QList as first element. You should convert the Qlist to a QVariant (not sure you want 2 level deep array, but right now you do). You QList<QVariantMap> and QVariantList is QList<QVariant>.

Right now if it could do something with the QList you would get this:
{"err":null,"letters":[[{"a": 1},{"b": 2},{"c": 3}]]}

Something like this, not sure this is possible declaration but you are looking to get this in the end. Or make a converter that convert your QList to a QVariantList if you still need that QList absolutely.

QVariantList letters {
                        QVariantMap {{"a",1}},
                        QVariantMap {{"b",2}},
                        QVariantMap {{"c",3}}
        };

Not tested just giving the idea
// can use traits if T is QVariant to simply convert by casting since it’s the same
Template<typename T>
QVariantList Convert<T>(const QList<T>& l)
{
                QVariantList rv;
                Rv.reserve(l.size());
                for(auto i in l)
                {
                                rv.append(QVariant::fromValue(i));
}
return rv;
}


From: Interest <interest-bounces at qt-project.org> on behalf of Jason H <jhihn at gmx.com>
Date: Tuesday, June 8, 2021 at 4:23 PM
To: interestqt-project.org <interest at qt-project.org>
Subject: [Interest] QJsonDocument::fromVariant failing with list
I'm having trouble with QJsonDocument::fromVariant() is not handling arrays:

        QVariant list;

        QList<QVariantMap> letters {
                        QVariantMap {{"a",1}},
                        QVariantMap {{"b",2}},
                        QVariantMap {{"c",3}}
        };

        list.setValue(letters);
        map["err"] = QVariant(); // null
        map["letters"] = list;

        qDebug() << QJsonDocument::fromVariant(map)
                                .toJson(QJsonDocument::Compact);

Output:
{"err":null,"letters":null}

I'm expecting:
{"err":null,"letters":[{"a": 1},{"b": 2},{"c": 3}]}

The debugger (screenshot attached) sees it. Is this a bug or am I doing it wrong?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20210608/c91efcb0/attachment.html>


More information about the Interest mailing list