将QMap转换为JSON [英] Convert QMap to JSON

查看:1377
本文介绍了将QMap转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个QMap对象,我想将其转换为JSON.我很困惑如何实现这一目标.

I have a QMap object and I would like to convert it to JSON. I am confused how I would accomplish this.

我阅读了QT文档,说我可以使用QDataStream将QMap转换为JSON,但是QDataStream似乎可以转换文件: http://doc.qt.io/qt-4.8/datastreamformat.html

I read QT documentation saying that I can use QDataStream to convert QMap to JSON, but QDataStream seems to convert files: http://doc.qt.io/qt-4.8/datastreamformat.html

// c++
QMap<QString, int> myMap;

推荐答案

将地图转换为QVariantMap并自动将其转换为JSON文档最简单:

It would be easiest to convert the map to QVariantMap which can automatically be converted to a JSON document:

QMap<QString, int> myMap;
QVariantMap vmap;

QMapIterator<QString, int> i(myMap);
while (i.hasNext()) {
    i.next();
    vmap.insert(i.key(), i.value());
}

QJsonDocument json = QJsonDocument::fromVariant(vmap);

如果需要,可以通过QJsonObject::fromVariant()静态方法使用同一事物创建QJsonObject.尽管对于QJsonObject,您可以跳过转换为变体贴图的步骤,而只是在迭代贴图时手动填充对象:

The same thing can be used to create a QJsonObject if you want, via the QJsonObject::fromVariant() static method. Although for QJsonObject you can skip the conversion to variant map step and simply populate the object manually as you iterate the map:

QMap<QString, int> myMap;
QJsonObject json;

QMapIterator<QString, int> i(myMap);
while (i.hasNext()) {
    i.next();
    json.insert(i.key(), i.value());
}    

这篇关于将QMap转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆