cJSON是一个轻量级的C语言JSON解析库,它提供了简单易用的API,使得在C语言程序中处理JSON数据变得非常方便。cJSON库的主要优势包括高效性、轻量级、易用性和安全性。它广泛应用于Web服务器、嵌入式系统、物联网设备、移动应用以及API交互等场景。
cJSON库主要用于解析和生成JSON数据。它采用结构体数组来表示JSON的对象和数组,这种设计使得cJSON在处理JSON数据时更加高效和紧凑。
cJSON主要提供了以下几种数据类型:
以下是一个简单的示例代码,展示了如何使用cJSON库解析和生成JSON数据:
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
// 解析 JSON 字符串
const char *json_str = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
cJSON *root = cJSON_Parse(json_str);
if (root == NULL) {
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
return 1;
}
// 获取 JSON 对象中的值
cJSON *name = cJSON_GetObjectItemCaseSensitive(root, "name");
cJSON *age = cJSON_GetObjectItemCaseSensitive(root, "age");
cJSON *city = cJSON_GetObjectItemCaseSensitive(root, "city");
printf("Name: %s\n", name->valuestring);
printf("Age: %d\n", age->valueint);
printf("City: %s\n", city->valuestring);
// 生成 JSON 字符串
cJSON *new_root = cJSON_CreateObject();
cJSON_AddStringToObject(new_root, "name", "Jane");
cJSON_AddNumberToObject(new_root, "age", 25);
cJSON_AddStringToObject(new_root, "city", "Los Angeles");
char *new_json_str = cJSON_Print(new_root);
printf("New JSON: %s\n", new_json_str);
// 释放内存
cJSON_Delete(root);
cJSON_Delete(new_root);
free(new_json_str);
return 0;
}
在使用cJSON库时,需要注意正确释放分配的内存,以避免内存泄漏。
领取专属 10元无门槛券
手把手带您无忧上云