admin 管理员组

文章数量: 1184232


2024年3月20日发(作者:duplicating)

cJSON

是一个用于处理 JSON 数据的 C 语言库。

cJSON_Print

是该库中的一个函数,用于将

cJSON

结构体

表示的 JSON 数据转换(或“打印”)为格式化的字符串。这通常用于调试或生成人类可读的 JSON 输出。

下面是如何使用

cJSON_Print

的基本示例:

1.

2.

c

包含必要的头文件:

#include

#include

1.

2.

c

创建 JSON 对象:

cJSON *root = cJSON_CreateObject();

cJSON_AddStringToObject(root, "name", "John Doe");

cJSON_AddNumberToObject(root, "age", 30);

cJSON_AddBoolToObject(root, "is_student", cJSON_False);

1.

2.

c

使用

cJSON_Print

打印 JSON 数据:

char *json_string = cJSON_Print(root);

printf("%sn", json_string);

释放内存:

1.

当你使用

cJSON

创建或修改 JSON 数据时,需要手动管理内存。在你完成操作后,应该释放与 JSON 数

据相关的所有内存。

c

cJSON_Delete(root);

free(json_string);

完整的示例代码:

c

#include

#include

int main() {

1

cJSON *root = cJSON_CreateObject();

cJSON_AddStringToObject(root, "name", "John Doe");

cJSON_AddNumberToObject(root, "age", 30);

cJSON_AddBoolToObject(root, "is_student", cJSON_False);

char *json_string = cJSON_Print(root);

printf("%sn", json_string);

cJSON_Delete(root);

free(json_string);

return 0;

}

当你运行上述代码时,你应该会看到以下输出:

json

{

"name": "John Doe",

"age": 30,

"is_student": false

}

注意:确保在编译时链接

cJSON

库,并包含正确的头文件路径。

2


本文标签: 应该 数据 用于 内存 代码