@CesantaHQ
{
"name": "sensor_1",
"wifi": {
"enable": true,
"ssid": "MyWifiNetwork",
"password": "ы"
},
"location": {
"lat": 53.3413712,
"lon": -6.2396965
}
}
{
"name": "sensor_1",
"wifi": {
"enable": true,
"ssid": "MyWifiNetwork",
"password": "ы"
},
"location": {
"lat": 53.3413712,
"lon": -6.2396965
}
}
/* Configuration structure */
struct config {
char *name;
struct {
int enable;
char *ssid;
char *pass;
} wifi;
struct {
double lat;
double lon;
} location;
};
/* Parsing JSON -> C/C++ structure */
struct config c;
struct json_obj = parse(json_string);
c.name = json_obj.attr("name").to_string();
c.location.lat = json_obj.attr("location").attr("lat").to_double();
...
/* Generating C/C++ structure -> JSON */
struct config c;
struct json_obj = init_json_obj();
json_obj.add_string("name", "my_device");
struct json_obj l = json_obj.add_emty_obj("location");
l.add_double("lat", 1.2345);
l.add_double("lon", -4,5678);
...
cout << json_obj.to_string();
/* file config.h : configuration structure */
struct config {
char *name;
double latitude;
};
static struct mem_layout {
const char *name;
size_t offset;
int type;
} config_mem_layout = {
{"name", offsetof(struct config, name), TYPE_STRING},
{"latitude", offsetof(struct config, latitude), TYPE_NUMBER}
};
char *config_to_json(const struct config *cfg) {
/* Having a pointer and memory layout, we can serialize */
...
}
Running a tool gives us marshalling API:
/* file config_json.h : marshalling API */
char *config_to_json(const struct config *);
// str has the following JSON string (notice keys are out of order):
// { "a": 123, "c": true, "b": "hi" }
int a, b;
char *c;
json_scanf(str, strlen(str), "{ a:%d, b:%Q, c:%B }", &a, &b, &c);
// a == 123, b == "hi", c == true
json_printf(&out, "{%Q: %d, x: [%B, %B], y: %Q}", "foo", 123, 0, -1, "hi");
// Result:
// {"foo": 123, "x": [false, true], "y": "hi"}
contact me at
sergey.lyubka@cesanta.com