json-gen-c is a program for searializing C struct to JSON and deserializing JSON to C struct back. It parse structs' definition files then generate C codes to serialize and deserialize structs.
printf("marshal a[] to json> %s\n", sstr_cstr(json_str));
for (i = 0; i < 3; ++i) {
A_clear(&a[i]);
}
To Deserialize JSON to Structs
// const char *p_str = "{this is a json string}";
// sstr_t json_str = sstr(pstr);
struct A a;
A_init(&a);
json_unmarshal_A(json_str, &a); // json_str is a type of sstr_t
// ...
A_clear(&a);
To Deserialize JSON to Array of Structs
// const char *p_str = "[this is a json string]";
// sstr_t json_str = sstr(pstr);
struct A *a = NULL;
int len = 0;
json_unmarshal_array_A(&a, &len, json_str);
// ...
int i;
for (i = 0; i < len; ++i) {
A_clear(&a[i]);
}
free(a);
The Format of Structs Definition File
Define a struct like:
struct <struct_name> {
<field_type> <field_name> []?;
<field_type> <field_name> []?;
...
};
The field type can be one of the following:
int
long
float
double
sstr_t
bool
a struct name
If a field is an array, just append [] after the field name.
The JSON API
// initialize a struct
// always return 0
int <struct_name>_init(struct <struct_name> *obj);
// uninitialize a struct
// always return 0
int <struct_name>_clear(struct <struct_name> *obj);
// marshal a struct to json string.
// return 0 if success.
int json_marshal_<struct_name>(struct <struct_name>*obj, sstr_t out);
// marshal an array of struct to json string.
// return 0 if success.
int json_marshal_array_<struct_name>(struct <struct_name>*obj, int len, sstr_t out);
// unmarshal a json string to a struct.
// return 0 if success.
int json_unmarshal_<struct_name>(sstr_t in, struct <struct_name>*obj);
// unmarshal a json string to array of struct
// return 0 if success.
int json_unmarshal_<struct_name>(sstr_t in, struct <struct_name>**obj, int *len);
License
Codes of json-gen-c are licensed under GPL-3.0, except for the codes it generated. The copy right of the codes generated by json-gen-c is owned by the user who wrote the struct definition file, same as the copy right of a PDF file generated by Latex is owned by the user who wrote the tex file.