LeechCraft  0.6.70-16373-g319c272718
Modular cross-platform feature rich live environment.
json.h
Go to the documentation of this file.
1 /**********************************************************************
2  * LeechCraft - modular cross-platform feature rich internet client.
3  * Copyright (C) 2006-2014 Georg Rudoy
4  *
5  * Distributed under the Boost Software License, Version 1.0.
6  * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
7  **********************************************************************/
8 
9 #pragma once
10 
11 #include "sllconfig.h"
12 #include <stdexcept>
13 #include <QJsonArray>
14 #include <QJsonDocument>
15 #include <QJsonObject>
16 #include <QJsonValue>
17 
18 class QByteArray;
19 
20 namespace LC::Util
21 {
22  template<typename, typename>
23  class Either;
24 
25  UTIL_SLL_API Either<QString, QJsonDocument> ToJson (const QByteArray& json);
26 
27  class UTIL_SLL_API UnexpectedJson final : public std::runtime_error
28  {
29  public:
30  explicit UnexpectedJson (QJsonValue::Type expected, const QJsonValue&);
31  explicit UnexpectedJson (QJsonValue::Type expected, const QJsonDocument&);
32  };
33 
34  template<QJsonValue::Type Expected>
35  auto As (const QJsonValue& value)
36  {
37  if (value.type () != Expected) [[unlikely]]
38  throw UnexpectedJson { Expected, value };
39 
40  if constexpr (Expected == QJsonValue::Array)
41  return value.toArray ();
42  if constexpr (Expected == QJsonValue::Object)
43  return value.toObject ();
44  if constexpr (Expected == QJsonValue::String)
45  return value.toString ();
46  if constexpr (Expected == QJsonValue::Double)
47  return value.toDouble ();
48  if constexpr (Expected == QJsonValue::Bool)
49  return value.toBool ();
50  }
51 
52  template<QJsonValue::Type Expected>
53  requires (Expected == QJsonValue::Object || Expected == QJsonValue::Array)
54  auto As (const QJsonDocument& doc)
55  {
56  if constexpr (Expected == QJsonValue::Object)
57  {
58  if (doc.isObject ())
59  return doc.object ();
60  }
61  else if constexpr (Expected == QJsonValue::Array)
62  {
63  if (doc.isArray ())
64  return doc.array ();
65  }
66 
67  throw UnexpectedJson { Expected, doc };
68  }
69 
70 }
#define UTIL_SLL_API
Definition: sllconfig.h:16
Either< QString, QJsonDocument > ToJson(const QByteArray &json)
Definition: json.cpp:16
auto As(const QJsonValue &value)
Definition: json.h:35
Type
Describes the various types of XDG .desktop files.
Definition: itemtypes.h:23
requires(Tup1Size==Tup2Size) const expr auto ZipWith(Tup1 &&tup1