简体   繁体   English

Qt C ++从QJsonValue转换为QByteArray

[英]Qt C++ Conversion from QJsonValue to QByteArray

I have a large (megabytes) string in a QJsonValue , that I need to convert to QByteArray , as I am sending the string as data with a QNetworkRequest . 我在QJsonValue有一个大的(兆字节)字符串,我需要将其转换为QByteArray ,因为我将字符串作为数据发送到QNetworkRequest

Currently I am doing this: 目前我这样做:

myQJsonObject["myQJsonValue"].toString().toUtf8()

Would this incur copying the same data to memory many times for some reason? 由于某种原因,这会导致多次将相同的数据复制到内存中吗? If so, how would you go about implementing this without unnecessary copyings? 如果是这样,你如何在没有不必要的复制的情况下实现这一点?

and why you do not use QJsonDocument ? 为什么你不使用QJsonDocument This should be used for reading and writing. 这应该用于阅读和写作。 There is a method QJsonDocument::toBinaryData . 有一个方法QJsonDocument :: toBinaryData This API should do everything with most effective way. 这个API应该以最有效的方式完成所有事情。


Update to comment: 更新评论:

Single JSon value is must be one of other JSon types: object, string or some number. 单个JSon值必须是其他JSon类型之一:object,string或某个数字。 I'm pretty sure you have JSon object. 我很确定你有JSon对象。 So your code should look like this:: 所以你的代码应该是这样的::

JSonValue val = someJsond["someKey"];
if (val.isObject()) {
    QJSonDocument doc(val.toObject());
    SendToServer(doc.toBinaryData());
} else {
    // error or:
    SendToServer(val.toString().toUtf8());
}

The call to myQJsonObject["myQJsonValue"].toString() does not involve data copy thanks to copy-on-write semantics of Qt. 由于Qt的copy-on-write语义,对myQJsonObject["myQJsonValue"].toString()的调用不涉及数据复制。

The toUtf8 call is costly. toUtf8调用成本toUtf8 QString stores the data as Unicode (16-bit QChar s), and encoding it in UTF-8 involves more than data copy. QString将数据存储为Unicode(16位QChar ),并以UTF-8编码它不仅仅涉及数据复制。

QString::constData() returns a pointer to the underlying character array. QString::constData()返回指向底层字符数组的指针。 But then, each character is represented by 2 bytes instead of 1 or 2 bytes in case of Utf-8. 但是,在Utf-8的情况下,每个字符由2个字节而不是1或2个字节表示。 This might mean sending two times more data over the network. 这可能意味着通过网络发送两倍以上的数据。

So if your data consists of mostly ASCII characters, then UTF-8 is probably a better option. 因此,如果您的数据主要由ASCII字符组成,那么UTF-8可能是更好的选择。 If it contains lots of non-Ascii characters, and the other side can handle UTF-16, then UTF-16 is worth considering. 如果它包含许多非Ascii字符,而另一方可以处理UTF-16,那么UTF-16值得考虑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM