关键词:QJsonObject、bsoncxx
bsoncxx提供了2个很好用的方法用来转换json到bson,然后,加工一下就可以了;
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <bsoncxx/json.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/document/element.hpp>
bsoncxx::document::view toBson(const QJsonObject &obj)
{
if(obj.isEmpty())
return ::bsoncxx::document::view();
QJsonDocument doc(obj);
std::string json=doc.toJson().data();
return bsoncxx::from_json(json).view();
}
QJsonObject toJson(bsoncxx::document::view view)
{
if(view.empty())
return QJsonObject();
std::string json=bsoncxx::to_json(view);
QJsonDocument doc=QJsonDocument::fromJson(QByteArray::fromStdString(json));
if(doc.isObject())
return doc.object();
else
return QJsonObject();
}
QString getString(bsoncxx::document::view view,
std::string key)
{
if(view.empty())
return QString();
bsoncxx::document::element element=view[key];
if(element.type() == bsoncxx::type::k_utf8)
{
std::string value=element.get_utf8().value.to_string();
return QString::fromStdString(value);
}
else
return QString();
}