QHash serialization for QByteArray

I am trying to serialize a QHash object and store it in a QByteArray (to be sent using QUDPSocket or QTCPSocket).

My current attempt is as follows:

// main.cpp #include <QtCore/QCoreApplication> #include <QHash> #include <QVariant> #include <QDebug> int main(int argc, char *argv[]) { QHash<QString,QVariant> hash; hash.insert("Key1",1); hash.insert("Key2","thing2"); QByteArray ba; QDataStream ds(&ba, QIODevice::WriteOnly); ds << hash; qDebug() << ds; } 

When this is done, I get this from qDebug() :

 QIODevice::read: WriteOnly device QIODevice::read: WriteOnly device QIODevice::read: WriteOnly device QVariant(, ) 

The documentation says this should be written to an array of bytes, but obviously this is not happening here. What am I doing wrong?

Qt 4.7.1 on OS-X

Thanks! -J

+4
source share
2 answers

The reason he fails is because he is trying to read from a write-only stream. Sequence:

 qDebug() << ds; --> QVariant::QVariant(QDataStream &s) --> QDataStream& operator>>(QDataStream &s, QVariant &p) --> void QVariant::load(QDataStream &s) 

This last method (and a few more downstream ones) is trying to read from the data stream to convert its contents to QVariant for display in qDebug . In other words, your real code is fine; debugging check fails.

You can check the contents of the byte array like this:

 qDebug() << ba.length() << ba.toHex(); 
+4
source

You can implement your program like this code:

 QHash<QString,QVariant> options; options["string"] = "my string"; options["bool"] = true; QByteArray ar; //Serializing QDataStream out(&ar,QIODevice::WriteOnly); // write the data out << options; //setting a new value options["string"] = "new string"; //Deserializing // read the data serialized from the file QDataStream in(&ar,QIODevice::ReadOnly); in >> options; qDebug() << "value: " << options.value("string"); 

ref

+1
source

Source: https://habr.com/ru/post/1332521/


All Articles