从json字符串将QVariant强制转换为QList <MyClass>

时间:2019-10-23 10:57:02

标签: c++ arrays json qt deserialization

我正在尝试从JSON反序列化MyClass

//MyClass.h
class MyClass : public QObject
{
    Q_OBJECT

public:
    MyClass();
    MyClass(const MyClass& other);
    ~MyClass();

    int Counter = 0;
    QString Name;
    QVector<QString> NamesList;
    QJsonObject toJson() const;

};
Q_DECLARE_METATYPE(MyClass);

json字符串是:

{
    "ClassList": [
        {
            "Counter": 100,
            "Name": "My Name",
            "NamesList": [
                "Name 1",
                "Name 2",
                "Name 3"
            ]
        },
        {
            "Counter": 5555,
            "Name": "2My Name",
            "NamesList": [
                "2Name 1",
                "2Name 2",
                "2Name 3"
            ]
        }
    ]
}

我可以通过以下方式获得QVariant中的ClassList:

QVariantMap json_map = DeserializeFromJson(text);
QVariant listVariant = json_map["ClassList"];

但是我无法将listVariant强制转换为QList<MyClass>。 我尝试了以下代码片段,每次结果为空时。

QList<MyClass> myList = listVariant.value<QList<MyClass> >(); // Empty
QList<MyClass> list = qvariant_cast<QList<MyClass>>(listVariant); // Empty

QSequentialIterable iterable = listVariant.value<QSequentialIterable>();
for each (QVariant it in iterable)
    {
        bool convertable = it.canConvert<MyClass>(); // false
        MyClass cl = it.value<MyClass>(); // Empty
        MyClass cl2 = qvariant_cast<MyClass>(it); // Empty

        QObject* object = qvariant_cast<QObject*>(it); // Empty
        MyClass* cl3 = qobject_cast<MyClass*>(object); // Empty

        QVariant var;
        var.setValue(it); 
        MyClass s2 = var.value<MyClass>(); // Empty
    }

2 个答案:

答案 0 :(得分:0)

您可以使用QVariantList代替QList<MyClass>

答案 1 :(得分:0)

变量listVariant包含带有QVariantList个项目的QVariantMap。要将listVariant分解为QList<MyClass>,应将QVariantMap转换为MyClass,然后将QVariantList转换为QList<MyClass>。您可以通过指定qvariant_cast模板来告诉Qt如何做:

template <>
MyClass qvariant_cast<MyClass>(const QVariant& v) {
    MyClass result;
    result.Counter = v.toMap()["Counter"].toInt();
    result.Name = v.toMap()["Name"].toString();
    result.NamesList = v.toMap()["NamesList"].toStringString();
}

template <>
QList<MyClass> qvariant_cast<QList<MyClass>>(const QVariant& v) {
    QList<MyClass> result;
    foreach(const QVariant& item : v.toList()) {
        result.push_back(qvariant_cast<MyClass>(item));
    }
    return result;
}