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);
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());
}