QDataStream序列化

C字符串

        char* str = "一二三";
        QByteArray data; 
        QDataStream dt(&data, QIODevice::ReadWrite); 
        dt << str;
        QDataStream In(&data, QIODevice::ReadWrite);  


        char* strOut=NULL;
        In >> strOut;
        cout << strOut << endl;
        delete[]strOut;
        QByteArray data; 
        QDataStream dt(&data, QIODevice::ReadWrite); 
        dt << QString::fromLocal8Bit("的方法法国");
        dt << QString::fromLocal8Bit("1123");


        QDataStream In(&data, QIODevice::ReadWrite);  

        QString a;
        QString b;
        In >> a;
        In >> b;
        cout << a.toLocal8Bit().toStdString().c_str() <<","<<b.toLocal8Bit().toStdString().c_str() << endl;

QList

        QList<int> ls;
        ls << 11 << 22;
        QByteArray data; 
        QDataStream dt(&data, QIODevice::ReadWrite); 
        dt << ls;




        QDataStream In(&data, QIODevice::ReadWrite); 

        QList<int> pl;
        In >> pl; 

        for each (auto& var in pl)
        {
            cout << var << endl;
        }

QMap


        QMap xx;
        xx[QString::fromLocal8Bit("一")] = 11;
        xx[QString::fromLocal8Bit("二")] = 11;
        QByteArray data; 
        QDataStream dt(&data, QIODevice::ReadWrite); 
        dt << xx;

        QDataStream In(&data, QIODevice::ReadWrite); 
        QMap vv;
        In >> vv; 


        QMap::const_iterator i;
        for (i = vv.constBegin(); i != vv.constEnd(); ++i)
        {
            cout<< i.key().toLocal8Bit().toStdString() << ":" << i.value()<;
        }

自定义结构体


typedef struct
{
    qint32 a;
    qint32 b;
    QString c;
}Teststruct;

inline QDataStream &operator<<(QDataStream &qDataStream,  Teststruct &dt)
{
    qDataStream << dt.a << dt.b << dt.c;
    return qDataStream;
}

inline QDataStream &operator>>(QDataStream &qDataStream,  Teststruct &dt)
{
    qDataStream >> dt.a >> dt.b >> dt.c;
    return qDataStream;
}

        Teststruct   xx = {1,2,QString::fromLocal8Bit("一二三")};

        QByteArray data; 
        QDataStream dt(&data, QIODevice::ReadWrite); 
        dt << xx;
        QDataStream In(&data, QIODevice::ReadWrite); 

        Teststruct Out;
        In >> Out;
        cout << Out.a << "," <<Out.b << ","<< Out.c.toLocal8Bit().toStdString() << endl;

你可能感兴趣的:(Qt)