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
版权声明:本文标题:cjson_print的用法 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1710910084a579164.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论