Search code examples
c++jsonqt

Converting JSON array to QByteArray


I have an array: [0xa,0x0b,0x0c]

This is stored in QJsonArray, I want to cover this to a QByteArray. I've been searching around for a solution and have come across several methods, this is what I have tried but its not right:

    QJsonObject::iterator itrBinary = objJSON.find(clsFileThread::mscszBinary);
    if ( itrBinary != objJSON.end() ) {
      QJsonArray aryBinary(itrBinary->toArray());
    //At this point aryBinary contains:
    //10,11,12 which is correct
      QJsonDocument doc(aryBinary);        
      QByteArray aryBytes(doc.toBinaryData());
    //Now aryBytes contains:
    //'q','b','j' why, how?
      qDebug() << aryBinary << aryBytes;
    }

After the qDebug I get:

    QJsonArray([10,11,12]) "qbjs\x01\x00\x00\x00\x18\x00\x00\x00\x06\x00\x00\x00\f\x00\x00\x00J\x01\x00\x00j\x01\x00\x00\x8A\x01\x00\x00"

What I want in QBytesArray is exactly what was put into the QJsonArray, 10, 11, 12.


Solution

  • Thank you to "eyllanesc" for input, I would have thought there would be a built in function to do this, but here is the solution:

        QJsonArray aryBinary(itrBinary->toArray());
        QJsonArray::iterator itrArray = aryBinary.begin();
        QByteArray aryBytes;
        while( itrArray != aryBinary.end() ) {
            aryBytes.append(static_cast<char>(itrArray->toInt()));
            itrArray++;
        }
        qDebug() << aryBinary << aryBytes;