Qt Json serialization

1.5k views Asked by At

I have a QVariant which can contain a double, a QString, a Foo object, or anything.

I would like to serialize my QVariant without knowing what it contains. I am trying to do the serialization like this:

QJsonObject jsonObject;
jsonObject["myObject"] = _variant.toJsonObject();

What function must I overload in Foo? Must I use Q_PROPERTY?

2

There are 2 answers

0
floppy12 On

According to this you should be able to convert any QVariant to QJSonObject

Now your question become : how to transform your Foo class to QVariant ?

I suggest you to add toQVariant and fromQVariant methods to Foo class to encapsulate this behavior ; the most convenient QVariant class is actually QVariantMap that you can use like this to serialize your Foo object

QVariant toVariant( Foo song ) {
   QVariantMap map;
   map.insert("album", wstring2Utf8(song.album()));
   map.insert("artist", wstring2Utf8(song.artist()));
   map.insert("duration", song.duration());
   map.insert("fingerprint", wstring2Utf8(song.fingerprint()));
   map.insert("genre", wstring2Utf8(song.genre()));
   map.insert("title", wstring2Utf8(song.title()));
   map.insert("year", song.year());
   return map;
}
1
b4hand On

I don't believe that you can do what you want directly. There is no way to convert an arbitrary object like Foo to a QJsonObject except by manually reading and writing the corresponding fields of the Foo object. Since QVariant has no way of knowing that your object supports that functionality, you won't be able to use QVariant directly. It may help you to follow the example provided by Qt for doing serialization:

http://doc.qt.io/qt-5/qtcore-json-savegame-example.html

Notice they have manual read and write methods for the Game object.