QByteArray 转json
时间: 2023-09-12 21:10:01 浏览: 53
可以使用 QJsonDocument 类来将 QByteArray 转换为 JSON 格式的数据。具体步骤如下:
1. 将 QByteArray 转换为 QString:
```cpp
QString jsonString = QString::fromUtf8(byteArray);
```
2. 将 QString 转换为 QJsonDocument 对象:
```cpp
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toUtf8());
```
3. 获取 QJsonObject 对象并进行操作:
```cpp
QJsonObject jsonObject = jsonDocument.object();
```
完整的代码示例:
```cpp
QByteArray byteArray = /* 从网络或文件中获取到的 JSON 数据 */;
QString jsonString = QString::fromUtf8(byteArray);
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toUtf8());
QJsonObject jsonObject = jsonDocument.object();
// 对 jsonObject 进行操作
```
需要注意的是,如果 QByteArray 中的数据不是有效的 JSON 格式,则转换过程可能会失败。因此,在进行转换之前,应该先检查 QByteArray 的数据是否正确。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)