qprotobufjsonserializer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. #include "qprotobufjsonserializer.h"
  26. #include "qprotobufmetaobject.h"
  27. #include "qprotobufmetaproperty.h"
  28. #include "qtprotobuflogging.h"
  29. #include <microjson.h>
  30. #include <QMetaProperty>
  31. using namespace QtProtobuf;
  32. namespace QtProtobuf {
  33. //! \private
  34. class QProtobufJsonSerializerPrivate final
  35. {
  36. Q_DISABLE_COPY_MOVE(QProtobufJsonSerializerPrivate)
  37. public:
  38. using Serializer = std::function<QByteArray(const QVariant&)>;
  39. using Deserializer = std::function<QVariant(QByteArray)>;
  40. struct SerializationHandlers {
  41. Serializer serializer; /*!< serializer assigned to class */
  42. Deserializer deserializer;/*!< deserializer assigned to class */
  43. };
  44. using SerializerRegistry = std::unordered_map<int/*metatypeid*/, SerializationHandlers>;
  45. static QByteArray serializeFloat(const QVariant &propertyValue) {
  46. bool ok = false;
  47. float value = propertyValue.toFloat(&ok);
  48. if (!ok) {
  49. return QByteArray("NaN");
  50. }
  51. return QString::number(static_cast<double>(value), 'g').toUtf8();
  52. }
  53. static QByteArray serializeString(const QVariant &propertyValue) {
  54. return QString("\"%1\"").arg(propertyValue.toString()).toUtf8() ;
  55. }
  56. static QByteArray serializeBytes(const QVariant &propertyValue) {
  57. return QByteArray("\"") + propertyValue.toByteArray().toBase64() + "\"";
  58. }
  59. template<typename L>
  60. static QByteArray serializeList(const QVariant &propertyValue) {
  61. L listValue = propertyValue.value<L>();
  62. QByteArray result("[");
  63. for (auto value : listValue) {
  64. result += QString::number(value) + ",";
  65. }
  66. if (listValue.size() > 0) {
  67. result.resize(result.size() - 1);//Remove trailing `,`
  68. }
  69. result += "]";
  70. return result;
  71. }
  72. static QByteArray serializeDoubleList(const QVariant &propertyValue) {
  73. DoubleList listValue = propertyValue.value<DoubleList>();
  74. QByteArray result("[");
  75. for (auto value : listValue) {
  76. result += QString::number(value, 'g').toUtf8() + ",";
  77. }
  78. if (listValue.size() > 0) {
  79. result.resize(result.size() - 1);//Remove trailing `,`
  80. }
  81. result += "]";
  82. return result;
  83. }
  84. static QByteArray serializeStringList(const QVariant &propertyValue) {
  85. QStringList listValue = propertyValue.value<QStringList>();
  86. QByteArray result("[");
  87. for (auto value : listValue) {
  88. result += QByteArray("\"") + value.toUtf8() + "\",";
  89. }
  90. if (listValue.size() > 0) {
  91. result.resize(result.size() - 1);//Remove trailing `,`
  92. }
  93. result += "]";
  94. return result;
  95. }
  96. static QByteArray serializeBytesList(const QVariant &propertyValue) {
  97. QByteArrayList listValue = propertyValue.value<QByteArrayList>();
  98. QByteArray result("[");
  99. for (auto value : listValue) {
  100. result += QByteArray("\"") + value.toBase64() + "\",";
  101. }
  102. if (listValue.size() > 0) {
  103. result.resize(result.size() - 1);//Remove trailing `,`
  104. }
  105. result += "]";
  106. return result;
  107. }
  108. QProtobufJsonSerializerPrivate(QProtobufJsonSerializer *q) : qPtr(q) {
  109. if (handlers.empty()) {
  110. handlers[qMetaTypeId<QtProtobuf::int32>()] = {{}, QProtobufJsonSerializerPrivate::deserializeInt32};
  111. handlers[qMetaTypeId<QtProtobuf::sfixed32>()] = {{}, QProtobufJsonSerializerPrivate::deserializeInt32};
  112. handlers[qMetaTypeId<QtProtobuf::sint32>()] = {{}, QProtobufJsonSerializerPrivate::deserializeInt32};
  113. handlers[qMetaTypeId<QtProtobuf::sint64>()] = {{}, QProtobufJsonSerializerPrivate::deserializeInt64};
  114. handlers[qMetaTypeId<QtProtobuf::int64>()] = {{}, QProtobufJsonSerializerPrivate::deserializeInt64};
  115. handlers[qMetaTypeId<QtProtobuf::sfixed64>()] = {{}, QProtobufJsonSerializerPrivate::deserializeInt64};
  116. handlers[qMetaTypeId<QtProtobuf::uint32>()] = {{}, QProtobufJsonSerializerPrivate::deserializeUInt32};
  117. handlers[qMetaTypeId<QtProtobuf::fixed32>()] = {{}, QProtobufJsonSerializerPrivate::deserializeUInt32};
  118. handlers[qMetaTypeId<QtProtobuf::uint64>()] = {{}, QProtobufJsonSerializerPrivate::deserializeUInt64};
  119. handlers[qMetaTypeId<QtProtobuf::fixed64>()] = {{}, QProtobufJsonSerializerPrivate::deserializeUInt64};
  120. handlers[qMetaTypeId<bool>()] = {{}, QProtobufJsonSerializerPrivate::deserializeBool};
  121. handlers[QMetaType::Float] = {QProtobufJsonSerializerPrivate::serializeFloat, QProtobufJsonSerializerPrivate::deserializeFloat};
  122. handlers[QMetaType::Double] = {{}, QProtobufJsonSerializerPrivate::deserializeDouble};
  123. handlers[QMetaType::QString] = {QProtobufJsonSerializerPrivate::serializeString, QProtobufJsonSerializerPrivate::deserializeString};
  124. handlers[QMetaType::QByteArray] = {QProtobufJsonSerializerPrivate::serializeBytes, QProtobufJsonSerializerPrivate::deserializeByteArray};
  125. handlers[qMetaTypeId<QtProtobuf::int32List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::int32List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::int32>};
  126. handlers[qMetaTypeId<QtProtobuf::int64List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::int64List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::int64>};
  127. handlers[qMetaTypeId<QtProtobuf::sint32List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::sint32List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::sint32>};
  128. handlers[qMetaTypeId<QtProtobuf::sint64List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::sint64List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::sint64>};
  129. handlers[qMetaTypeId<QtProtobuf::uint32List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::uint32List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::uint32>};
  130. handlers[qMetaTypeId<QtProtobuf::uint64List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::uint64List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::uint64>};
  131. handlers[qMetaTypeId<QtProtobuf::fixed32List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::fixed32List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::fixed32>};
  132. handlers[qMetaTypeId<QtProtobuf::fixed64List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::fixed64List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::fixed64>};
  133. handlers[qMetaTypeId<QtProtobuf::sfixed32List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::sfixed32List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::sfixed32>};
  134. handlers[qMetaTypeId<QtProtobuf::sfixed64List>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::sfixed64List>, QProtobufJsonSerializerPrivate::deserializeList<QtProtobuf::sfixed64>};
  135. handlers[qMetaTypeId<QtProtobuf::FloatList>()] = {QProtobufJsonSerializerPrivate::serializeList<QtProtobuf::FloatList>, QProtobufJsonSerializerPrivate::deserializeList<float>};
  136. handlers[qMetaTypeId<QtProtobuf::DoubleList>()] = {QProtobufJsonSerializerPrivate::serializeDoubleList, QProtobufJsonSerializerPrivate::deserializeList<double>};
  137. handlers[qMetaTypeId<QStringList>()] = {QProtobufJsonSerializerPrivate::serializeStringList, QProtobufJsonSerializerPrivate::deserializeStringList};
  138. handlers[qMetaTypeId<QByteArrayList>()] = {QProtobufJsonSerializerPrivate::serializeBytesList, QProtobufJsonSerializerPrivate::deserializeList<QByteArray>};
  139. }
  140. }
  141. ~QProtobufJsonSerializerPrivate() = default;
  142. QByteArray serializeValue(const QVariant &propertyValue, const QProtobufMetaProperty &metaProperty) {
  143. QByteArray buffer;
  144. auto userType = propertyValue.userType();
  145. auto &value = QtProtobufPrivate::findHandler(userType);
  146. if (value.serializer) {
  147. value.serializer(qPtr, propertyValue, metaProperty, buffer);
  148. } else {
  149. auto handler = handlers.find(userType);
  150. if (handler != handlers.end() && handler->second.serializer) {
  151. buffer += handler->second.serializer(propertyValue);
  152. } else {
  153. buffer += propertyValue.toString().toUtf8();
  154. }
  155. }
  156. return buffer;
  157. }
  158. QByteArray serializeProperty(const QVariant &propertyValue, const QProtobufMetaProperty &metaProperty) {
  159. return QByteArray("\"") + metaProperty.protoPropertyName().toUtf8() + "\":" + serializeValue(propertyValue, metaProperty);
  160. }
  161. QByteArray serializeObject(const QObject *object, const QProtobufMetaObject &metaObject) {
  162. QByteArray result = "{";
  163. for (const auto &field : metaObject.propertyOrdering) {
  164. int propertyIndex = field.second;
  165. int fieldIndex = field.first;
  166. Q_ASSERT_X(fieldIndex < 536870912 && fieldIndex > 0, "", "fieldIndex is out of range");
  167. QMetaProperty metaProperty = metaObject.staticMetaObject.property(propertyIndex);
  168. const char *propertyName = metaProperty.name();
  169. const QVariant &propertyValue = object->property(propertyName);
  170. result.append(serializeProperty(propertyValue, QProtobufMetaProperty(metaProperty, fieldIndex)));
  171. result.append(",");
  172. }
  173. result.resize(result.size() - 1);//Remove trailing `,`
  174. result.append("}");
  175. return result;
  176. }
  177. static QVariant deserializeInt32(const QByteArray &data) {
  178. return QVariant::fromValue(data.toInt());
  179. }
  180. static QVariant deserializeUInt32(const QByteArray &data) {
  181. return QVariant::fromValue(data.toUInt());
  182. }
  183. static QVariant deserializeInt64(const QByteArray &data) {
  184. return QVariant::fromValue(data.toLongLong());
  185. }
  186. static QVariant deserializeUInt64(const QByteArray &data) {
  187. return QVariant::fromValue(data.toULongLong());
  188. }
  189. static QVariant deserializeFloat(const QByteArray &data) {
  190. return QVariant::fromValue(data.toFloat());
  191. }
  192. static QVariant deserializeDouble(const QByteArray &data) {
  193. return QVariant::fromValue(data.toDouble());
  194. }
  195. static QVariant deserializeBool(const QByteArray &data) {
  196. return QVariant::fromValue(QString::fromUtf8(data));
  197. }
  198. static QVariant deserializeString(const QByteArray &data) {
  199. return QVariant::fromValue(QString::fromUtf8(data).replace("\\\"", "\""));
  200. }
  201. static QVariant deserializeByteArray(const QByteArray &data) {
  202. return QVariant::fromValue(QByteArray::fromBase64(data));
  203. }
  204. template<typename T>
  205. static QVariant deserializeList(const QByteArray &data) {
  206. QList<T> list;
  207. auto arrayValues = microjson::parseJsonArray(data.data(), static_cast<size_t>(data.size()));
  208. auto handler = handlers.find(qMetaTypeId<T>());
  209. if (handler == handlers.end() || !handler->second.deserializer) {
  210. qProtoWarning() << "Unable to deserialize simple type list. Could not find desrializer for type" << qMetaTypeId<T>();
  211. return QVariant::fromValue(list);
  212. }
  213. for (auto &arrayValue : arrayValues) {
  214. QVariant newValue = handler->second.deserializer(QByteArray::fromStdString(arrayValue.value));
  215. list.append(newValue.value<T>());
  216. }
  217. return QVariant::fromValue(list);
  218. }
  219. static QVariant deserializeStringList(const QByteArray &data) {
  220. QStringList list;
  221. auto arrayValues = microjson::parseJsonArray(data.data(), static_cast<size_t>(data.size()));
  222. for (auto &arrayValue : arrayValues) {
  223. QVariant newValue = deserializeString(QByteArray::fromStdString(arrayValue.value));
  224. list.append(newValue.value<QString>());
  225. }
  226. return QVariant::fromValue(list);
  227. }
  228. void deserializeObject(QObject *object, const QProtobufMetaObject &metaObject, const char *data, int size) {
  229. microjson::JsonObject obj = microjson::parseJsonObject(data, static_cast<size_t>(size));
  230. for (auto &property : obj) {
  231. auto name = property.first;
  232. int propertyIndex = metaObject.staticMetaObject.indexOfProperty(name.data());
  233. if (propertyIndex >= 0) {
  234. QMetaProperty metaProperty = metaObject.staticMetaObject.property(propertyIndex);
  235. auto userType = metaProperty.userType();
  236. auto &handler = QtProtobufPrivate::findHandler(userType);
  237. QByteArray value = QByteArray::fromStdString(property.second.value);
  238. if (handler.deserializer) {
  239. QVariant newValue;
  240. if (property.second.type == microjson::JsonArrayType) {
  241. microjson::JsonArray arrayValues = microjson::parseJsonArray(property.second.value.data(), property.second.value.size());
  242. if (arrayValues.size() > 0) {
  243. if (arrayValues[0].type == microjson::JsonObjectType) {
  244. for (auto &arrayValue : arrayValues) {
  245. QByteArray arrayBuffer = QByteArray::fromStdString(arrayValue.value);
  246. QtProtobuf::QProtobufSelfcheckIterator it(arrayBuffer);
  247. handler.deserializer(qPtr, it, newValue);
  248. }
  249. } else {
  250. QtProtobuf::QProtobufSelfcheckIterator it(value);
  251. handler.deserializer(qPtr, it, newValue);
  252. }
  253. }
  254. } else {
  255. QtProtobuf::QProtobufSelfcheckIterator it(value);
  256. handler.deserializer(qPtr, it, newValue);
  257. }
  258. object->setProperty(name.c_str(), newValue);
  259. } else {
  260. auto handler = handlers.find(metaProperty.userType());
  261. if (handler != handlers.end() && handler->second.deserializer) {
  262. object->setProperty(name.c_str(), handler->second.deserializer(value));
  263. }
  264. }
  265. }
  266. }
  267. }
  268. private:
  269. static SerializerRegistry handlers;
  270. QProtobufJsonSerializer *qPtr;
  271. };
  272. QProtobufJsonSerializerPrivate::SerializerRegistry QProtobufJsonSerializerPrivate::handlers = {};
  273. }
  274. QProtobufJsonSerializer::QProtobufJsonSerializer() : dPtr(new QProtobufJsonSerializerPrivate(this))
  275. {
  276. }
  277. QProtobufJsonSerializer::~QProtobufJsonSerializer() = default;
  278. QByteArray QProtobufJsonSerializer::serializeMessage(const QObject *object, const QProtobufMetaObject &metaObject) const
  279. {
  280. return dPtr->serializeObject(object, metaObject);
  281. }
  282. void QProtobufJsonSerializer::deserializeMessage(QObject *object, const QProtobufMetaObject &metaObject, const QByteArray &data) const
  283. {
  284. dPtr->deserializeObject(object, metaObject, data.data(), data.size());
  285. }
  286. QByteArray QProtobufJsonSerializer::serializeObject(const QObject *object, const QProtobufMetaObject &metaObject, const QProtobufMetaProperty &/*metaProperty*/) const
  287. {
  288. return dPtr->serializeObject(object, metaObject);
  289. }
  290. void QProtobufJsonSerializer::deserializeObject(QObject *object, const QProtobufMetaObject &metaObject, QProtobufSelfcheckIterator &it) const
  291. {
  292. dPtr->deserializeObject(object, metaObject, it.data(), it.size());
  293. }
  294. QByteArray QProtobufJsonSerializer::serializeListBegin(const QProtobufMetaProperty &/*metaProperty*/) const
  295. {
  296. return {"["};
  297. }
  298. QByteArray QProtobufJsonSerializer::serializeListObject(const QObject *object, const QProtobufMetaObject &metaObject, const QProtobufMetaProperty &/*metaProperty*/) const
  299. {
  300. return dPtr->serializeObject(object, metaObject) + ",";
  301. }
  302. QByteArray QProtobufJsonSerializer::serializeListEnd(QByteArray &buffer, const QProtobufMetaProperty &/*metaProperty*/) const
  303. {
  304. if (buffer[buffer.size() - 1] == ',') {
  305. buffer.resize(buffer.size() - 1);
  306. }
  307. return {"]"};
  308. }
  309. void QProtobufJsonSerializer::deserializeListObject(QObject *object, const QProtobufMetaObject &metaObject, QProtobufSelfcheckIterator &it) const
  310. {
  311. dPtr->deserializeObject(object, metaObject, it.data(), it.size());
  312. }
  313. QByteArray QProtobufJsonSerializer::serializeMapBegin(const QProtobufMetaProperty &/*metaProperty*/) const
  314. {
  315. return {"{"};
  316. }
  317. QByteArray QProtobufJsonSerializer::serializeMapPair(const QVariant &key, const QVariant &value, const QProtobufMetaProperty &metaProperty) const
  318. {
  319. return QByteArray("\"") + key.toString().toUtf8() + "\":" + dPtr->serializeValue(value, metaProperty) + ",";
  320. }
  321. QByteArray QProtobufJsonSerializer::serializeMapEnd(QByteArray &buffer, const QProtobufMetaProperty &/*metaProperty*/) const
  322. {
  323. if (buffer[buffer.size() - 1] == ',') {
  324. buffer.resize(buffer.size() - 1);
  325. }
  326. return {"}"};
  327. }
  328. void QProtobufJsonSerializer::deserializeMapPair(QVariant &key, QVariant &value, QProtobufSelfcheckIterator &it) const
  329. {
  330. Q_UNUSED(key)
  331. Q_UNUSED(value)
  332. Q_UNUSED(it)
  333. }
  334. QByteArray QProtobufJsonSerializer::serializeEnum(int64 value, const QMetaEnum &metaEnum, const QtProtobuf::QProtobufMetaProperty &/*metaProperty*/) const
  335. {
  336. return QByteArray("\"") + metaEnum.key(static_cast<int>(value)) + "\"";
  337. }
  338. QByteArray QProtobufJsonSerializer::serializeEnumList(const QList<int64> &values, const QMetaEnum &metaEnum, const QtProtobuf::QProtobufMetaProperty &/*metaProperty*/) const
  339. {
  340. QByteArray result = "[";
  341. for (auto value : values) {
  342. result.append("\"");
  343. result.append(metaEnum.key(static_cast<int>(value)));
  344. result.append("\",");
  345. }
  346. if (values.size() > 0) {
  347. result.resize(result.size() - 1);
  348. }
  349. result.append("]");
  350. return result;
  351. }
  352. void QProtobufJsonSerializer::deserializeEnum(int64 &value, const QMetaEnum &metaEnum, QProtobufSelfcheckIterator &it) const
  353. {
  354. value = metaEnum.keyToValue(it.data());
  355. }
  356. void QProtobufJsonSerializer::deserializeEnumList(QList<int64> &value, const QMetaEnum &metaEnum, QProtobufSelfcheckIterator &it) const
  357. {
  358. auto arrayValues = microjson::parseJsonArray(it.data(), static_cast<size_t>(it.size()));
  359. for (auto &arrayValue : arrayValues) {
  360. value.append(metaEnum.keyToValue(arrayValue.value.c_str()));
  361. }
  362. }