-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjson_helpers.hpp
62 lines (53 loc) · 2.21 KB
/
json_helpers.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Nonolith Connect
// https://github.com/nonolith/connect
// Helper functions for extracting typed data from JSON
// Released under the terms of the GNU GPLv3+
// (C) 2012 Nonolith Labs, LLC
// Authors:
// Kevin Mehall <[email protected]>
struct ErrorStringException : public std::exception{
string s;
ErrorStringException (string ss) throw() : s(ss) {}
virtual const char* what() const throw() { return s.c_str(); }
virtual ~ErrorStringException() throw() {}
};
inline string jsonStringProp(JSONNode &n, const char* prop){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_STRING) return i->as_string();
else throw ErrorStringException(string("JSON missing string property: ") + prop);
}
inline bool jsonBoolProp(JSONNode &n, const char* prop){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_BOOL) return i->as_bool();
else throw ErrorStringException(string("JSON missing bool property: ") + prop);
}
inline int jsonIntProp(JSONNode &n, const char* prop){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_NUMBER) return i->as_int();
else throw ErrorStringException(string("JSON missing int property: ") + prop);
}
inline double jsonFloatProp(JSONNode &n, const char* prop){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_NUMBER) return i->as_float();
else throw ErrorStringException(string("JSON missing float property: ") + prop);
}
inline string jsonStringProp(JSONNode &n, const char* prop, string def){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_STRING) return i->as_string();
else return def;
}
inline int jsonIntProp(JSONNode &n, const char* prop, int def){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_NUMBER) return i->as_int();
else return def;
}
inline bool jsonBoolProp(JSONNode &n, const char* prop, bool def){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_BOOL) return i->as_bool();
else return def;
}
inline double jsonFloatProp(JSONNode &n, const char* prop, double def){
JSONNode::iterator i = n.find(prop);
if (i != n.end() && i->type() == JSON_NUMBER) return i->as_float();
else return def;
}