-
Notifications
You must be signed in to change notification settings - Fork 1
Home
sveinb edited this page Jun 21, 2013
·
5 revisions
This library consists of two .cpp files and two .h files. If you just want to parse a JSON string into a C++ data structure defined by the library, all you need is the decodeJSON.cpp / decodeJSON.h files. Example:
char *jsonstring = (char *)"{ \"a\": 1, \"b\": \"hello\", \"c\": [5,6,7] }";
Object *v=(Object *)decodeJSON(jsonstring);
Number *a=(Number *)v->properties["a"];
cout << "a=" << a->n << "\n";
However, if you have your own C++ classes that you want to populate with data from a JSON string, you would then have to check the data types of every element you come across, which is a lot of tedious work. The easy way is to use the files JSONschema.cpp / JSONschema.h. Example:
class MyClass {
public:
// === JSON hooks to be inserted here ===
double a;
string b;
vector<double> c;
};
char *jsonstring = (char *)"{ \"a\": 1, \"b\": \"hello\", \"c\": [5,6,7] }";
MyClass myObject;
if (!decodeJSON(jsonstring, new Object<MyClass>, &myObject))
exit(1);
cout << "a=" << myObject.a << "\n";
In addition to the strict JSON format, decodeJSON supports
- C-style comments (line and block comments)
- Double and single quotes for strings (must match)
- Object property names without quotes
If you know that you're going to use JSONschema, then decodeJSON will be hidden from you and you can skip its documentation entirely.