Qt: Convert Struct to QJsonObject and QJsonObject to Struct
To convert from a struct to a QJsonObject, you can create a function that iterates over the struct's members and adds them to the QJsonObject. Here is an example:
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
struct MyStruct {
int id;
QString name;
bool active;
};
QJsonObject structToJsonObject(const MyStruct& myStruct) {
QJsonObject jsonObject;
jsonObject['id'] = myStruct.id;
jsonObject['name'] = myStruct.name;
jsonObject['active'] = myStruct.active;
return jsonObject;
}
int main() {
MyStruct myStruct{1, 'John', true};
QJsonObject jsonObject = structToJsonObject(myStruct);
QJsonDocument jsonDoc(jsonObject);
qDebug() << jsonDoc.toJson();
return 0;
}
To convert from a QJsonObject to a struct, you can create a function that extracts the values from the QJsonObject and assigns them to the struct members. Here is an example:
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
struct MyStruct {
int id;
QString name;
bool active;
};
MyStruct jsonObjectToStruct(const QJsonObject& jsonObject) {
MyStruct myStruct;
myStruct.id = jsonObject['id'].toInt();
myStruct.name = jsonObject['name'].toString();
myStruct.active = jsonObject['active'].toBool();
return myStruct;
}
int main() {
QString jsonStr = R"({\n "id": 1,\n "name": "John",\n "active": true\n })" ;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8());
QJsonObject jsonObject = jsonDoc.object();
MyStruct myStruct = jsonObjectToStruct(jsonObject);
qDebug() << "id:" << myStruct.id;
qDebug() << "name:" << myStruct.name;
qDebug() << "active:" << myStruct.active;
return 0;
}
Note: These examples assume you have the necessary Qt libraries and headers included. Make sure to include the appropriate headers and link against the necessary libraries for your project.
原文地址: https://www.cveoy.top/t/topic/p0Ec 著作权归作者所有。请勿转载和采集!