问题描述
我有一个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!