libdisplaydevice v2026.322.2407
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
11namespace display_device {
12 // A shared "toJson" implementation. Extracted here for UTs + coverage.
13 template<typename Type>
14 std::string toJsonHelper(const Type &obj, const std::optional<unsigned int> &indent, bool *success) {
15 try {
16 if (success) {
17 *success = true;
18 }
19
20 nlohmann::json json_obj = obj;
21 return json_obj.dump(static_cast<int>(indent.value_or(-1)));
22 } catch (const std::exception &err) { // GCOVR_EXCL_BR_LINE for fallthrough branch
23 if (success) {
24 *success = false;
25 }
26
27 return err.what();
28 }
29 }
30
31 // A shared "fromJson" implementation. Extracted here for UTs + coverage.
32 template<typename Type>
33 bool fromJsonHelper(const std::string &string, Type &obj, std::string *error_message = nullptr) {
34 try {
35 if (error_message) {
36 error_message->clear();
37 }
38
39 Type parsed_obj = nlohmann::json::parse(string);
40 obj = std::move(parsed_obj);
41 return true;
42 } catch (const std::exception &err) {
43 if (error_message) {
44 *error_message = err.what();
45 }
46
47 return false;
48 }
49 }
50
51 #define DD_JSON_DEFINE_CONVERTER(Type) \
52 std::string toJson(const Type &obj, const std::optional<unsigned int> &indent, bool *success) { \
53 return toJsonHelper(obj, indent, success); \
54 } \
55 bool fromJson(const std::string &string, Type &obj, std::string *error_message) { \
56 return fromJsonHelper<Type>(string, obj, error_message); \
57 }
58} // namespace display_device
59#endif