0
votes
#include "QtCore"
#include "QMap"
#include "qdebug.h"
#include "qjsondocument.h"



class cclass{
public:
    int var;
};
Q_DECLARE_METATYPE(cclass);


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

cclass object1;
object1.var=40;

 QVariant variant= QVariant::fromValue(object1);


  QVariantMap map;
    map.insert("variant",variant);



 QJsonDocument document=  QJsonDocument::fromVariant(map);

 qDebug()<<document;

    return a.exec();
}

qdebug returns QJsonDocument({"variant":null}) I think it should be returning the values of object1 but it returns null.why so? I want to pair string and a class in json using qt.how can i do it

1
from Qt docs If the variant contains any other type than a QVariantMap, QVariantHash, QVariantList or QStringList, the returned document is invalid. - Simon
but its a qvariatmap only - karan sharma

1 Answers

0
votes

Because of the way QVariant handles custom types.

From the Qt docs, Note: If you are working with custom types, you should use the Q_DECLARE_METATYPE() macro to register your custom type.

In other words, QVariant::fromValue() doesn't know what to do with your cclass type and simply create a null QVariant, which is then serialized accordingly in the QJsonDocument.