Skip to content

Convenient way to make 'basic_json' accept 'QString' as an key type as well? #1640

Closed
@FlKo

Description

I want to use Qt's QString type with the excellent nlohmann::json.
This works very well by providing the functions to_json and from_json as described in the readme:

nljson.h

#include <QString>
#include <QByteArray>
#include <vector>
#include "nlohmann/fifo_map.hpp"
#include "nlohmann/json.hpp"

// This is a workaround solution for the "nlohmann::json" library to preserve
// the insertion order of JSON objects instead of sorting them by name.
// It is based on a custom map implementation by Niels Lohmann itself
// (nlohmann::fifo_map). The actual solution (by GitHub user "Daniel599")
// can be found here: https://github.com/nlohmann/json/issues/485#issuecomment-333652309
template<class K, class V, class dummyCompare, class A>
using nljson_fifo_map = nlohmann::fifo_map<K, V, nlohmann::fifo_map_compare<K>, A>;
using nljson = nlohmann::basic_json<nljson_fifo_map>;

QT_BEGIN_NAMESPACE
void to_json(nljson &j, const QString &qstr);
void from_json(const nljson j, QString &qstr);

void to_json(nljson &j, const QByteArray &qba);
void from_json(nljson &j, QByteArray &qba);
QT_END_NAMESPACE

nljson.cpp

#include "qnljson.h"

#include <QString>
#include <QByteArray>
#include <string>
#include "nlohmann/json.hpp"

QT_BEGIN_NAMESPACE

void to_json(nljson &j, const QString &qstr)
{
    j = nljson { qstr.toStdString() };
}

void from_json(const nljson j, QString &qstr)
{
    if (j.type() == qnljson::value_t::string)
        qstr = QString::fromStdString(j.get<std::string>());
    else
        qstr = QString::fromStdString(j.dump());
}

void to_json(nljson &j, const QByteArray &qba)
{
    j = qnljson { qba.toStdString() };
}

void from_json(nljson &j, QByteArray &qba)
{
    qba = QByteArray::fromStdString(j.get<std::string>());
}

QT_END_NAMESPACE

However, I would find it very beneficial if it were possible to use QString as a key data type as well:

myfile.cpp

// {...}
QString foo = "abc";
nljson bar { "a", foo };
QString baz = "a";

qDebug() << bar.at(baz).get<QString>(); // Error: no viable conversion from 'QString' to 'int'

qDebug() << bar.at(baz.toStdString()).get<QString>(); // This works

Is there a convenient way to make nlohmann::json accept QString as a key type without this explicit conversion (baz.toStdString())?

Metadata

Assignees

No one assigned

    Labels

    kind: questionstate: stalethe issue has not been updated in a while and will be closed automatically soon unless it is updated

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions