Skip to content

Instantly share code, notes, and snippets.

@atomass
Last active May 25, 2018 14:41
Show Gist options
  • Save atomass/cccc0169a2b1809daec7dfa23dc09c5b to your computer and use it in GitHub Desktop.
Save atomass/cccc0169a2b1809daec7dfa23dc09c5b to your computer and use it in GitHub Desktop.
Serialize QObject derived class into QJsonDocument
#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
@atomass
Copy link
Author

atomass commented May 24, 2018

The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro. The function is recursive, so if the class has members that inherit from QObject, declared with Q_PROPERTY they will be added to the JsonObject.

TODO:

  • Manage arrays
  • Manage empty objects on Deserialize
  • Create Deserializer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment