eduwin JSON API
eduwin 内置 cJSON 引擎,提供简洁的 JSON 解析与构建接口。
类型
typedef struct cJSON json_t;
json_t 即 cJSON 结构体,所有 JSON API 均通过此指针操作。
解析与释放
json_t *json_parse(const char *utf8);
void json_free(json_t *obj);
json_parse 解析 UTF-8 编码的 JSON 字符串,返回根对象指针。解析失败返回 NULL。
json_free 释放整个 JSON 树。解析得到的对象使用完毕后必须调用此函数释放内存。
json_t *root = json_parse(str);
if (!root) { /* 解析失败 */ }
/* ... 读取数据 ... */
json_free(root);
读取值
int json_get_int(json_t *obj, const char *key);
double json_get_double(json_t *obj, const char *key);
const char *json_get_str(json_t *obj, const char *key);
json_t *json_get_obj(json_t *obj, const char *key);
json_t *json_get_arr(json_t *obj, const char *key);
从 JSON 对象中按 key 读取对应字段。key 不存在或类型不匹配时返回默认值(0 / 0.0 / NULL)。
json_t *root = json_parse(str);
int score = json_get_int(root, "score");
const char *name = json_get_str(root, "name");
json_t *child = json_get_obj(root, "config");
json_t *items = json_get_arr(root, "items");
数组操作
int json_arr_size(json_t *arr);
json_t *json_arr_get(json_t *arr, int index);
json_arr_size 返回数组元素个数。json_arr_get 按索引获取数组元素(从 0 开始)。
int n = json_arr_size(arr);
for (int i = 0; i < n; i++)
{
json_t *item = json_arr_get(arr, i);
const char *name = json_get_str(item, "name");
}
构建 JSON
json_t *json_create_obj(void);
json_t *json_create_arr(void);
json_t *json_create_str(const char *val);
json_t *json_create_num(double val);
创建空的 JSON 对象或数组。
void json_add_int(json_t *obj, const char *key, int val);
void json_add_double(json_t *obj, const char *key, double val);
void json_add_str(json_t *obj, const char *key, const char *val);
void json_add_obj(json_t *obj, const char *key, json_t *val);
void json_add_arr(json_t *obj, const char *key, json_t *val);
void json_arr_add(json_t *arr, json_t *item);
向对象或数组中添加字段/元素。json_add_obj 和 json_add_arr 会将传入的 json_t* 所有权移交给父对象,不要再对子对象调用 json_free。
json_t *root = json_create_obj();
json_t *arr = json_create_arr();
json_add_str(root, "name", "张三");
json_add_int(root, "age", 18);
json_add_arr(root, "scores", arr);
json_arr_add(arr, json_create_int(95));
json_arr_add(arr, json_create_int(88));
char *out = json_to_str(root); /* {"name":"张三","age":18,"scores":[95,88]} */
free(out);
json_free(root);
输出为字符串
char *json_to_str(json_t *root);
char *json_to_str_min(json_t *root);
json_to_str 返回格式化的 JSON 字符串(带缩进换行)。json_to_str_min 返回压缩的 JSON 字符串(无空白字符)。返回的字符串需要调用 free() 释放。