trajopt
 All Classes Namespaces Files Functions Variables Typedefs Pages
json_marshal.hpp
1 #pragma once
2 #include <json/json.h>
3 #include <vector>
4 #include <boost/format.hpp>
5 #include <string>
6 #include <sstream>
7 #include "macros.h"
8 
9 
10 namespace json_marshal {
11 
12 TRAJOPT_API void fromJson(const Json::Value& v, bool& ref);
13 TRAJOPT_API void fromJson(const Json::Value& v, int& ref);
14 TRAJOPT_API void fromJson(const Json::Value& v, double& ref);
15 TRAJOPT_API void fromJson(const Json::Value& v, std::string& ref);
16 template <class T>
17 inline void fromJson(const Json::Value& v, T& ref) {
18  ref.fromJson(v);
19 }
20 template <class T>
21 void fromJsonArray(const Json::Value& parent, std::vector<T>& ref) {
22  ref.clear();
23  ref.reserve(parent.size());
24  for (Json::Value::const_iterator it = parent.begin(); it != parent.end(); ++it) {
25  T t;
26  fromJson(*it, t);
27  ref.push_back(t);
28  }
29 }
30 template <class T>
31 void fromJsonArray(const Json::Value& parent, std::vector<T>& ref, int size) {
32  if (parent.size() != size) {
33  PRINT_AND_THROW(boost::format("expected list of size size %i. got: %s\n")%size%parent);
34  }
35  else {
36  fromJsonArray(parent, ref);
37  }
38 }
39 template <class T>
40 inline void fromJson(const Json::Value& v, std::vector<T>& ref) {
41  fromJsonArray(v, ref);
42 }
43 
44 template <class T>
45 void childFromJson(const Json::Value& parent, T& ref, const char* name, const T& df) {
46  if (parent.isMember(name)) {
47  const Json::Value& v = parent[name];
48  fromJson(v, ref);
49  }
50  else {
51  ref = df;
52  }
53 }
54 template <class T>
55 void childFromJson(const Json::Value& parent, T& ref, const char* name) {
56  if (parent.isMember(name)) {
57  const Json::Value& v = parent[name];
58  fromJson(v, ref);
59  }
60  else {
61  PRINT_AND_THROW(boost::format("missing field: %s")%name);
62  }
63 }
64 
65 
66 
67 
68 }