design a template auto convet a struct to qjsonobject
Sure, here's a template that can be used to automatically convert a struct to a QJsonObject:
#include <QJsonObject>
#include <QJsonArray>
// Helper function to convert a value to QJsonValue
template<typename T>
QJsonValue toQJsonValue(const T& value)
{
return QJsonValue::fromVariant(QVariant::fromValue(value));
}
// Helper function to convert a struct to QJsonObject
template<typename T>
QJsonObject toQJsonObject(const T& data)
{
QJsonObject jsonObject;
// Iterate over each member variable in the struct
// and add it to the QJsonObject
QMetaObject metaObject = T::staticMetaObject;
for (int i = 0; i < metaObject.propertyCount(); ++i) {
QMetaProperty metaProperty = metaObject.property(i);
const char* propertyName = metaProperty.name();
QVariant propertyValue = metaProperty.readOnGadget(&data);
// Handle different data types
if (propertyValue.type() == QVariant::List) {
QJsonArray jsonArray;
QList<QVariant> list = propertyValue.toList();
for (const QVariant& element : list) {
jsonArray.append(toQJsonValue(element));
}
jsonObject[propertyName] = jsonArray;
} else if (propertyValue.type() == QVariant::Map) {
QJsonObject nestedJsonObject;
QMap<QString, QVariant> map = propertyValue.toMap();
for (const QString& key : map.keys()) {
nestedJsonObject[key] = toQJsonValue(map.value(key));
}
jsonObject[propertyName] = nestedJsonObject;
} else {
jsonObject[propertyName] = toQJsonValue(propertyValue);
}
}
return jsonObject;
}
To use this template, you need to define your struct with Q_GADGET macro and add Q_PROPERTY declarations for each member variable. Here's an example:
#include <QDebug>
struct MyStruct {
Q_GADGET
Q_PROPERTY(QString name MEMBER name)
Q_PROPERTY(int age MEMBER age)
Q_PROPERTY(QList<QString> hobbies MEMBER hobbies)
Q_PROPERTY(QMap<QString, QVariant> data MEMBER data)
public:
QString name;
int age;
QList<QString> hobbies;
QMap<QString, QVariant> data;
};
int main()
{
MyStruct myStruct;
myStruct.name = "John";
myStruct.age = 25;
myStruct.hobbies = {"Reading", "Gaming"};
myStruct.data = {{"key1", 10}, {"key2", "value"}};
QJsonObject jsonObject = toQJsonObject(myStruct);
qDebug() << jsonObject;
return 0;
}
This template will automatically convert the struct to a QJsonObject, handling different data types such as QString, int, QList, QMap, etc
原文地址: http://www.cveoy.top/t/topic/iium 著作权归作者所有。请勿转载和采集!