Page MenuHomePhorge

qt-json.hpp
No OneTemporary

Size
2 KB
Referenced Files
None
Subscribers
None

qt-json.hpp

/*
* This file is part of kazv.
* SPDX-FileCopyrightText: 2020-2024 tusooa <tusooa@kazv.moe>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
#include <kazv-defs.hpp>
#include <nlohmann/json.hpp>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <cmath>
inline void to_json(nlohmann::json& j, const QJsonObject& qj);
inline void from_json(const nlohmann::json& j, QJsonObject& qj);
inline void to_json(nlohmann::json& j, const QJsonArray& qj);
inline void from_json(const nlohmann::json& j, QJsonArray& qj);
inline void to_json(nlohmann::json& j, const QJsonValue& qj);
inline void to_json(nlohmann::json& j, const QJsonValue& qj);
inline void to_json(nlohmann::json& j, const QJsonValue& qj) {
if (qj.isArray()) {
j = qj.toArray();
} else if (qj.isObject()) {
j = qj.toObject();
} else if (qj.isBool()) {
j = qj.toBool();
} else if (qj.isDouble()) {
// Qt's json library does not distinguish between the numeric types
// and stores them all as doubles.
// nlohmann's json, however, differentiate between integers and
// floating point numbers, and will serialize them differently.
// Prefer using ints here, because canonical json in the Matrix spec
// uses ints, not floats.
auto num = qj.toDouble();
auto floor = std::floor(num);
if (floor == num) {
j = static_cast<long long>(floor);
} else {
j = num;
}
} else if (qj.isString()) {
j = qj.toString().toStdString();
}
}
inline void from_json(const nlohmann::json& j, QJsonValue& qj) {
if (j.is_array()) {
qj = QJsonValue(j.get<QJsonArray>());
} else if (j.is_object()) {
qj = QJsonValue(j.get<QJsonObject>());
} else if (j.is_boolean()) {
qj = QJsonValue(j.get<bool>());
} else if (j.is_number()) {
qj = QJsonValue(j.get<double>());
} else if (j.is_string()) {
qj = QJsonValue(QString::fromStdString(j.get<std::string>()));
} else if (j.is_null()) {
qj = QJsonValue();
}
}
inline void to_json(nlohmann::json& j, const QJsonObject& qj) {
for (auto it = qj.constBegin(); it != qj.constEnd(); ++it) {
j[it.key().toStdString()] = it.value();
}
}
inline void from_json(const nlohmann::json& j, QJsonObject& qj) {
for (const auto &[k, v]: j.items()) {
qj.insert(QString::fromStdString(k), v.get<QJsonValue>());
}
}
inline void to_json(nlohmann::json& j, const QJsonArray& qj) {
for (const auto &i: qj) {
j.push_back(i);
}
}
inline void from_json(const nlohmann::json& j, QJsonArray& qj) {
for (const auto &i: j) {
qj.push_back(i.get<QJsonValue>());
}
}

File Metadata

Mime Type
text/x-c
Expires
Sun, Nov 24, 2:48 AM (22 h, 24 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
39284
Default Alt Text
qt-json.hpp (2 KB)

Event Timeline