Visual Servoing Platform  version 3.6.1 under development (2024-12-17)
vpJsonParsing.h
1 /*
2  * ViSP, open source Visual Servoing Platform software.
3  * Copyright (C) 2005 - 2024 by Inria. All rights reserved.
4  *
5  * This software is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * See the file LICENSE.txt at the root directory of this source
10  * distribution for additional information about the GNU GPL.
11  *
12  * For using ViSP with software that can not be combined with the GNU
13  * GPL, please contact Inria about acquiring a ViSP Professional
14  * Edition License.
15  *
16  * See https://visp.inria.fr for more information.
17  *
18  * This software was developed at:
19  * Inria Rennes - Bretagne Atlantique
20  * Campus Universitaire de Beaulieu
21  * 35042 Rennes Cedex
22  * France
23  *
24  * If you have questions regarding the use of this file, please contact
25  * Inria at visp@inria.fr
26  *
27  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
28  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
29  *
30  * Description:
31  * JSON parsing helpers.
32  */
33 
34 #ifndef VP_JSON_PARSING_H
35 #define VP_JSON_PARSING_H
36 
37 #include <visp3/core/vpConfig.h>
38 
39 #ifdef VISP_HAVE_NLOHMANN_JSON
40 #include VISP_NLOHMANN_JSON(json.hpp)
41 
42 BEGIN_VISP_NAMESPACE
54 template<typename E>
55 int flagsFromJSON(const nlohmann::json &j)
56 {
57  int flags = 0;
58  if (j.is_array()) {
59  flags = 0;
60  for (const auto &v : j) {
61  E value = v.get<E>(); // If a value is incorrect, this will default to the first value of the enum
62  flags |= value;
63  }
64  }
65  else if (j.is_number_integer()) {
66  flags = j.get<int>();
67  }
68  return flags;
69 }
70 
79 template<typename E>
80 nlohmann::json flagsToJSON(const int flags, const std::vector<E> &options)
81 {
82  nlohmann::json j = nlohmann::json::array();
83  for (const E option : options) {
84  if (flags & option) {
85  j.push_back(option);
86  }
87  }
88  return j;
89 }
90 
91 template<typename T>
92 bool convertFromTypeAndBuildFrom(const nlohmann::json &, T &)
93 {
94  return false;
95 }
96 
97 template<typename T, typename O, typename... Os>
98 bool convertFromTypeAndBuildFrom(const nlohmann::json &j, T &t)
99 {
100  if (j["type"] == O::jsonTypeName) {
101  O other;
102  from_json(j, other);
103  t.buildFrom(other);
104  return true;
105  }
106  else {
107  return convertFromTypeAndBuildFrom<T, Os...>(j, t);
108  }
109 }
110 END_VISP_NAMESPACE
111 #endif
112 #endif