Last active
May 25, 2018 14:41
-
-
Save atomass/cccc0169a2b1809daec7dfa23dc09c5b to your computer and use it in GitHub Desktop.
Serialize QObject derived class into QJsonDocument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef JSONHELPER_H | |
#define JSONHELPER_H | |
#include <QJsonObject> | |
#include <QMetaProperty> | |
class JSONHelper | |
{ | |
public: | |
template<class T> | |
static void Deserialize(T* arg, const QJsonObject &jobject) | |
{ | |
const QMetaObject* metaObject = arg->metaObject(); | |
foreach (QString k, jobject.keys()) { | |
const char* kc = k.toLower().toStdString().c_str(); | |
int propIndex = metaObject->indexOfProperty(kc); | |
if ( propIndex < 0 ) | |
continue; | |
QVariant variant = arg->property(kc); | |
if ( jobject[k].isObject() ) { | |
if (variant.canConvert<QObject *>()) { | |
// Both jobject and the property are objects | |
QObject* obj = variant.value<QObject *>(); | |
if ( !obj ){ | |
// TODO: create object | |
continue; | |
} | |
// Iterate | |
Deserialize<QObject>(obj, jobject[k].toObject()); | |
} | |
} else { | |
QVariant debug_variant = jobject[k].toVariant(); | |
bool success = arg->setProperty(kc, debug_variant); | |
qDebug() << success; | |
} | |
} | |
} | |
template<class T> | |
static const QJsonObject Serialize(const T *arg) | |
{ | |
QJsonObject jobj; | |
const QMetaObject* metaObject = arg->metaObject(); | |
for(int i = metaObject->propertyOffset(); i < metaObject->propertyCount(); ++i) { | |
QMetaProperty prop = metaObject->property(i); | |
QVariant variant = arg->property(prop.name()); | |
if ( variant.canConvert<QObject *>() ) { | |
QObject* sub_obj = variant.value<QObject*>(); | |
jobj.insert( prop.name(), Serialize<QObject>(sub_obj) ); | |
} else | |
jobj.insert(prop.name(), QJsonValue::fromVariant(arg->property(prop.name()))); | |
} | |
return jobj; | |
} | |
private: | |
JSONHelper(); | |
}; | |
#endif // JSONHELPER_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The class
T
must inherit (directly or indirectly)QObject
and be declared with theQ_OBJECT
macro. The function is recursive, so if the class has members that inherit fromQObject
, declared withQ_PROPERTY
they will be added to theJsonObject
.TODO: