armink/struct2json
FreeA fast convert library between the JSON and C structure. Implement structure serialization and deserialization for C. | C 结构体与 JSON 快速互转库,快速实现 C 结构体的序列化及反序列化
FreeFree tier
About armink/struct2json
struct2json is an open-source C library that provides fast conversion between C structures and JSON. It wraps the cJSON library to offer a simple API for serializing C struct objects into JSON strings and deserializing JSON back into C structs. The library supports nested structures, arrays, and int64 data types. A Python script is included to auto-generate conversion code from C header files. Use cases include data persistence (e.g., saving to Flash), inter-language communication, and visualization for debugging.
Key Features
Fast serialization and deserialization between C structs and JSON
Simple API based on cJSON library
Supports nested structs (struct within struct)
Supports array members (including one-dimensional arrays of basic types and structs)
Supports int64 (long long) data types without precision loss
Python script to auto-generate conversion code from C header files
MIT open-source license
Pros & Cons
Pros
- Open source with MIT license, free to use
- Significantly reduces code complexity compared to using raw cJSON for struct conversion
- Automates conversion code generation for large header files via Python script
- Lightweight and focused on embedded or resource-constrained environments
Cons
- Limited to C language; no support for C++ or other languages
- Depends on cJSON library (a dependency to manage)
- Does not support union or bit-field members (union/bit-field treated as int)
- Enum and pointer members are treated as integers, which may lose semantic information
Best For
Persistence: Save struct objects to file or Flash memory as JSONCommunication: Use JSON as protocol between C and other languages (e.g., JavaScript, Groovy)Visualization: Display struct data on console or UI for debugging and secondary development
FAQ
What is struct2json?
struct2json is an open-source C library that enables fast conversion between C structures and JSON format, wrapping the cJSON library for serialization and deserialization.
What are the main use cases for struct2json?
It is primarily used for persistence (saving structs to file or Flash), communication (as a protocol between C and other languages), and visualization (displaying struct data for debugging).
Does struct2json support nested structures?
Yes, version 2.0 added support for structures containing other structures as members, as well as array members.
How can I generate conversion code automatically?
struct2json includes a Python script (generate_s2j_code.py) that extracts struct definitions from C header files and automatically generates the serialization/deserialization code.
What license is struct2json under?
The library is released under the MIT License.