Linux C: cJSON 库使用指南 - 解析和生成 JSON 数据
cJSON 是一个轻量级的 JSON 解析器和生成器库,可以在 Linux 系统中使用。以下是使用 cJSON 库的简单示例:
-
首先,你需要从 cJSON 官方网站 (https://github.com/DaveGamble/cJSON) 下载 cJSON 库的源代码并解压。
-
在你的 C 代码中,包含 cJSON 库的头文件:
#include 'cJSON.h' -
在你的 C 代码中,使用 cJSON 库的函数来解析和生成 JSON 数据。
解析 JSON 数据的示例代码:
const char* json_data = '{"name":"John", "age":30, "city":"New York"}'; cJSON* root = cJSON_Parse(json_data); if (root != NULL) { cJSON* name = cJSON_GetObjectItem(root, 'name'); cJSON* age = cJSON_GetObjectItem(root, 'age'); cJSON* city = cJSON_GetObjectItem(root, 'city'); if (name != NULL && age != NULL && city != NULL) { printf("Name: %s\n", name->valuestring); printf("Age: %d\n", age->valueint); printf("City: %s\n", city->valuestring); } cJSON_Delete(root); }生成 JSON 数据的示例代码:
cJSON* root = cJSON_CreateObject(); cJSON_AddStringToObject(root, 'name', 'John'); cJSON_AddNumberToObject(root, 'age', 30); cJSON_AddStringToObject(root, 'city', 'New York'); char* json_data = cJSON_Print(root); printf("%s\n", json_data); free(json_data); cJSON_Delete(root);
注意:使用 cJSON 库时,需要在编译时链接 cJSON 库的二进制文件。详细的编译和链接步骤请参考 cJSON 库的文档。
原文地址: https://www.cveoy.top/t/topic/qhlM 著作权归作者所有。请勿转载和采集!