Flavio Castelli

Debugging my life.

QJson: Easier Serialization of QObject Instances to JSON

| Comments

I have just committed into trunk a couple of changes that make easier to serialize a QObject instance to JSON.

This solution relies on the awesome Qt’s property system.

Suppose the declaration of Person class looks like this:

[class definition] [ ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Person : public QObject
{
  Q_OBJECT
    Q_PROPERTY(QString name READ name WRITE setName)
    Q_PROPERTY(int phoneNumber READ phoneNumber WRITE setPhoneNumber)
    Q_PROPERTY(Gender gender READ gender WRITE setGender)
    Q_PROPERTY(QDate dob READ dob WRITE setDob)
    Q_ENUMS(Gender)
  public:
    Person(QObject* parent = 0);
    ~Person();
    QString name() const;
    void setName(const QString& name);
    int phoneNumber() const;
    void setPhoneNumber(const int  phoneNumber);
    enum Gender {Male, Female};
    void setGender(Gender gender);
    Gender gender() const;
    QDate dob() const;
    void setDob(const QDate& dob);
  private:
    QString m_name;
    int m_phoneNumber;
    Gender m_gender;
    QDate m_dob;
};

The following code will serialize an instance of Person to JSON:

[Serialize to JSON] [ ]
1
2
3
4
5
6
7
    Person person;
    person.setName("Flavio");
    person.setPhoneNumber(123456);
    person.setGender(Person::Male);
    person.setDob(QDate(1982, 7, 12));
    Serializer serializer;
    qDebug() << serializer.serialize( &person;);

The generated output will be:

[JSON data] [ ]
1
    { "dob" : "1982-07-12", "gender" : 0, "name" : "Flavio", "phoneNumber" : 123456 }

I hope you will find this new feature useful. I’m also considering to create a similar method inside the Parser class.

As usual suggestions are welcome.

Comments