File indexing completed on 2025-01-12 07:20:49
0001 /* 0002 SPDX-FileCopyrightText: 2018 Volker Krause <vkrause@kde.org> 0003 0004 SPDX-License-Identifier: LGPL-2.0-or-later 0005 */ 0006 0007 #ifndef KPUBLICTRANSPORT_JSON_P_H 0008 #define KPUBLICTRANSPORT_JSON_P_H 0009 0010 #include <QJsonArray> 0011 #include <QJsonObject> 0012 #include <QStringList> 0013 0014 #include <vector> 0015 0016 struct QMetaObject; 0017 0018 namespace KPublicTransport { 0019 0020 /** De/serialization helper methods. */ 0021 namespace Json 0022 { 0023 /** Looks for a translated value in @p obj with @p key. */ 0024 QString translatedValue(const QJsonObject &obj, const QString &key); 0025 /** Convert a QJsonValue to a QStringList, assuming it contains an array of strings. */ 0026 QStringList toStringList(const QJsonValue &v); 0027 0028 QJsonObject toJson(const QMetaObject *mo, const void *elem); 0029 0030 /** Serialize from QMetaObject. */ 0031 template <typename T> inline QJsonObject toJson(const T &elem) 0032 { 0033 return toJson(&T::staticMetaObject, &elem); 0034 } 0035 0036 /** Serialize an array of elements. */ 0037 template <typename T> inline QJsonArray toJson(const std::vector<T> &elems) 0038 { 0039 QJsonArray a; 0040 //a.reserve(elems.size()); 0041 std::transform(elems.begin(), elems.end(), std::back_inserter(a), QOverload<const T&>::of(&T::toJson)); 0042 return a; 0043 } 0044 0045 void fromJson(const QMetaObject *mo, const QJsonObject &obj, void *elem); 0046 0047 /** Deserialize via QMetaObject. */ 0048 template <typename T> inline T fromJson(const QJsonObject &obj) 0049 { 0050 T elem; 0051 fromJson(&T::staticMetaObject, obj, &elem); 0052 return elem; 0053 } 0054 0055 /** Deserialize an array of elements. */ 0056 template <typename T> inline std::vector<T> fromJson(const QJsonArray &a) 0057 { 0058 std::vector<T> res; 0059 res.reserve(a.size()); 0060 std::transform(a.begin(), a.end(), std::back_inserter(res), [](const auto &v) { return T::fromJson(v.toObject()); }); 0061 return res; 0062 } 0063 } 0064 0065 } 0066 0067 #endif // KPUBLICTRANSPORT_JSON_P_H