struct2json is an open source C structure and JSON fast interconversion library. It can quickly realize the serialization and deserialization requirements between structure objects and JSON objects . The fast and concise API design greatly reduces the code complexity of directly using the JSON parsing library to implement such functions.
Applying object-oriented design to C language is a very popular design idea at the moment. Since there are no classes in the C language, the structure struct
is generally used as a class, and the structure variables are objects. After having an object, you often need to consider the serialization and deserialization of the object. Unlike many high-level languages, C language has mechanisms such as reflection, so that object serialization and deserialization are natively supported.
For C language, serializing into JSON strings is a good choice, so you have to use a JSON parsing library such as cJSON. However, the code after use is redundant and has poor logic, so I came up with a secondary encapsulation of the cJSON library to implement A library for fast conversion between struct and JSON. This is where struct2json was born. The following are the main usage scenarios of struct2json:
Two structures are declared as follows. The structure Hometown
is a substructure of the structure Student
/* 籍贯 */
typedef struct {
char name [ 16 ];
} Hometown ;
/* 学生 */
typedef struct {
uint8_t id ;
uint8_t score [ 8 ];
char name [ 10 ];
double weight ;
Hometown hometown ;
} Student ;
Before use (source file) | After use (source file) |
---|---|
Before use (source file) | After use (source file) |
---|---|
将头文件(eg:mc_usr_def.h)放在demoinc目录下;
执行generate_struct_defination.py,生成struct_defination.txt;
执行generate_s2j_code.py,根据结构体定义自动生成结构体与JSON互转代码:my_struct_2_json.c,my_struct_2_json.h;
该脚本支持的参数类型有 基本类型 和 结构体类型,enum和指针按int处理,不支持union和位域;
支持的数组类型:支持基本类型一维数组,结构体一维数组,字符二维数组(字符串数组)
cd demo
编译测试代码,gcc ../cJSON/cJSON.c ../struct2json/src/*.c ./*.c -I ../cJSON/ -I ../struct2json/inc/ -lm -DDEBUGS2J -g -o tests2j
测试 ./tests2j
查看output输出和生成的JSON样例文件struct_defination.json;
预期输出:*:strcmp:0 *:strcmp:0
*:json_cmp:1
Welcome everyone to fork and pull request (Github|OSChina|Coding). If you think this open source project is great, you can click Star in the upper right corner of the project homepage and recommend it to more friends in need.
For specific content, please refer to the files under docszh
. Be sure to read the documentation before using it.
MIT Copyright (c) [email protected]