libdisplaydevice master
C++ library to modify display devices.
json_converter.h
Go to the documentation of this file.
1
5#pragma once
6
7#ifdef DD_JSON_DETAIL
8 // system includes
9 #include <nlohmann/json.hpp>
10 #include <stdexcept>
11
12namespace display_device {
13 // A shared "toJson" implementation. Extracted here for UTs + coverage.
14 template<typename Type>
15 std::string toJsonHelper(const Type &obj, const std::optional<unsigned int> &indent, bool *success) {
16 try {
17 if (success) {
18 *success = true;
19 }
20
21 nlohmann::json json_obj = obj;
22 return json_obj.dump(static_cast<int>(indent.value_or(-1)));
23 } catch (const nlohmann::json::exception &err) { // GCOVR_EXCL_BR_LINE for fallthrough branch
24 if (success) {
25 *success = false;
26 }
27
28 return err.what();
29 } catch (const std::out_of_range &err) { // GCOVR_EXCL_BR_LINE for fallthrough branch
30 if (success) {
31 *success = false;
32 }
33
34 return err.what();
35 } catch (const std::invalid_argument &err) { // GCOVR_EXCL_BR_LINE for fallthrough branch
36 if (success) {
37 *success = false;
38 }
39
40 return err.what();
41 }
42 }
43
44 // A shared "fromJson" implementation. Extracted here for UTs + coverage.
45 template<typename Type>
46 bool fromJsonHelper(const std::string &string, Type &obj, std::string *error_message = nullptr) {
47 try {
48 if (error_message) {
49 error_message->clear();
50 }
51
52 Type parsed_obj = nlohmann::json::parse(string);
53 obj = std::move(parsed_obj);
54 return true;
55 } catch (const nlohmann::json::exception &err) {
56 if (error_message) {
57 *error_message = err.what();
58 }
59
60 return false;
61 } catch (const std::out_of_range &err) {
62 if (error_message) {
63 *error_message = err.what();
64 }
65
66 return false;
67 } catch (const std::invalid_argument &err) {
68 if (error_message) {
69 *error_message = err.what();
70 }
71
72 return false;
73 }
74 }
75
76 #define DD_JSON_DEFINE_CONVERTER(Type) \
77 std::string toJson(const Type &obj, const std::optional<unsigned int> &indent, bool *success) { \
78 return toJsonHelper(obj, indent, success); \
79 } \
80 bool fromJson(const std::string &string, Type &obj, std::string *error_message) { \
81 return fromJsonHelper<Type>(string, obj, error_message); \
82 }
83} // namespace display_device
84#endif