localeconverter.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "localeconverter_p.h"
  2. #include "exception.h"
  3. #include "cborserializer.h"
  4. #include <QtCore/QLocale>
  5. using namespace QtJsonSerializer;
  6. using namespace QtJsonSerializer::TypeConverters;
  7. bool LocaleConverter::canConvert(int metaTypeId) const
  8. {
  9. return metaTypeId == QMetaType::QLocale;
  10. }
  11. QList<QCborTag> LocaleConverter::allowedCborTags(int metaTypeId) const
  12. {
  13. Q_UNUSED(metaTypeId)
  14. return {
  15. static_cast<QCborTag>(CborSerializer::LocaleISO),
  16. static_cast<QCborTag>(CborSerializer::LocaleBCP47),
  17. };
  18. }
  19. QList<QCborValue::Type> LocaleConverter::allowedCborTypes(int metaTypeId, QCborTag tag) const
  20. {
  21. Q_UNUSED(metaTypeId)
  22. Q_UNUSED(tag)
  23. return {QCborValue::String};
  24. }
  25. int LocaleConverter::guessType(QCborTag tag, QCborValue::Type dataType) const
  26. {
  27. return allowedCborTags(QMetaType::UnknownType).contains(tag) &&
  28. dataType == QCborValue::String;
  29. }
  30. QCborValue LocaleConverter::serialize(int propertyType, const QVariant &value) const
  31. {
  32. Q_UNUSED(propertyType)
  33. if (helper()->getProperty("useBcp47Locale").toBool())
  34. return {static_cast<QCborTag>(CborSerializer::LocaleBCP47), value.toLocale().bcp47Name()};
  35. else
  36. return {static_cast<QCborTag>(CborSerializer::LocaleISO), value.toLocale().name()};
  37. }
  38. QVariant LocaleConverter::deserializeCbor(int propertyType, const QCborValue &value, QObject *parent) const
  39. {
  40. Q_UNUSED(propertyType)
  41. Q_UNUSED(parent)
  42. const auto strValue = (value.isTag() ? value.taggedValue() : value).toString();
  43. QLocale locale{strValue};
  44. if (locale == QLocale::c()) {
  45. if (strValue.toUpper() == QLatin1Char('C') ||
  46. strValue.isEmpty())
  47. return QLocale::c();
  48. else
  49. throw DeserializationException("String cannot be interpreted as locale");
  50. } else
  51. return locale;
  52. }