简体   繁体   中英

QJsonDocument giving null when converting from Qvariant?

#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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM