Skip to content

Instantly share code, notes, and snippets.

@pylvain
Created June 25, 2020 15:26
Show Gist options
  • Save pylvain/d8127d4a3da206fcd49dd05463a4cc07 to your computer and use it in GitHub Desktop.
Save pylvain/d8127d4a3da206fcd49dd05463a4cc07 to your computer and use it in GitHub Desktop.
Convertion between Qt JSON and nlohmann/json
#include "json/json.hpp"
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonObject>
using namespace nlohmann;
json::value_type jsonutils::fromQJsonValue(const QJsonValue &v)
{
if(v.isString())
return json::value_type(v.toString().toUtf8().constData());
if(v.isBool())
return json::value_type(v.toBool());
if(v.isDouble())
return json::value_type(v.toDouble());
if(v.isArray())
{
std::vector<json::value_type> ret;
for ( const auto & e : v.toArray())
{
ret.push_back(fromQJsonValue(e));
}
return ret;
}
if(v.isObject())
{
std::map<std::string, json::value_type> ret;
for ( const QString & e : v.toObject().keys())
{
ret[e.toUtf8().constData()] = fromQJsonValue(v[e]);
}
return ret;
}
return json::value_type();
}
QJsonValue jsonutils::toQJsonValue(const json::value_type &v)
{
if(v.is_string())
return QJsonValue(v.get<std::string>().c_str());
if(v.is_boolean())
return QJsonValue(v.get<bool>());
if(v.is_number())
return QJsonValue(v.get<double>());
if(v.is_array())
{
QJsonArray ret;
for(const auto & i : v.get<std::vector<json::value_type> >())
{
ret.append(toQJsonValue(i));
}
return QJsonValue(ret);
}
if(v.is_object())
{
QJsonObject ret;
for(const auto &[key,value] : v.get<std::map<std::string,json::value_type> >() )
{
ret[QString(key.c_str())] = toQJsonValue(value);
}
return QJsonValue(ret);
}
return QJsonValue();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment