使用到的QT库:
#include <QJsonObject>
#include <QJsonArray>
#include <QString>
#include <QJsonDocument>
#include <QObject>
假设json的数据为:
{ “name”:“xxx”, “age”:3, “langurage”:{ “国籍”:[“中”,“俄”,“土”] } }
定义类时,name,age,langurage为类的成员,langurage为类中的类:
#define PropertyBuilderByName(type, name, access_permission)\
access_permission:\
type m_##name;\
public:\
inline void set##name(type v) {\
m_##name = v;\
}\
inline type get##name() {\
return m_##name;\
}\
PropertyBuilderByName(QString,name,public)
PropertyBuilderByName(int,age,public)
public:
class Inside
{
public:
Inside(QList<QString> &ss){s=ss;}
QList<QString> gets() const {return s;}
private:
QList<QString> s;
};
xxx(QString name,int age,QList<QString> ss);
Inside getinside()
{
return inside;
}
QString FormToJson() const;
xxx xxx( const QString &json);
private:
Inside inside;
这里注意一下,由于类中有类,那么我的构造函数就这样写了:
xxx::xxx(QString name,int age ,QList<QString> ss):inside(ss)
{
setname(name);
setage(age);
}
类转换为json:
QString xxx::FormToJson() const
{
QJsonObject json;
json.insert(QStringLiteral("name"), m_name);
json.insert(QStringLiteral("age"), m_name);
QJsonObject insideObject;
QJsonArray ss;
for (const QString &sinside : inside.gets()) {
ss.append(sinside);
}
insideObject.insert(QStringLiteral("国籍"),ss);
json.insert(QStringLiteral("langurage"),insideObject);
return QJsonDocument(json).toJson();
}
json转换为类:
xxx xxx::formJson( const QString &json)
{
QJsonParseError error;
const QJsonDocument document = QJsonDocument::fromJson(json.toUtf8(),&error);
if(error.error==QJsonParseError::NoError)
{
const QJsonObject &obj = document.object();
const QString name = obj.value(QStringLiteral("name")).toString();
int age = obj.value(QStringLiteral("age")).toInt();
const QJsonObject &insideObject = obj.value(QStringLiteral("langurage")).toObject();
QJsonArray array = insideObject.value(QStringLiteral("国籍")).toArray();
QList<QString> ll;
for(const QJsonValue &ss : array)
{
ll.append(ss.toString());
}
return xxx(name,age,ll);
}
qDebug()<<"error"<<endl;
throw error.errorString();
}
|