如果你想使用cJSON库解析给定的JSON数据,可以按照以下步骤进行:
首先,确保已经将cJSON库正确地包含在你的项目中。你可以从cJSON官方网站下载并获取该库。
创建一个新的C文件,比如
parse_json.c,并将以下代码复制到该文件中:
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
// 提供的JSON数据
const char* jsonStr = "{\"siteName\":\"两江人和停车场换电站-1\",\"zipBase64\":{\"type\":\"Buffer\",\"data\":[80,75,3,4,10,0,0,0,0,0,221,81,142,88,...]}}";
// 解析JSON字符串
cJSON* root = cJSON_Parse(jsonStr);
if (root == NULL) {
printf("解析JSON失败\n");
return 1;
}
// 获取siteName字段值
cJSON* siteNameNode = cJSON_GetObjectItemCaseSensitive(root, "siteName");
if (siteNameNode != NULL && siteNameNode->type == cJSON_String) {
printf("Site Name: %s\n", siteNameNode->valuestring);
} else {
printf("无法获取Site Name字段\n");
}
// 获取zipBase64字段值
cJSON* zipBase64Node = cJSON_GetObjectItemCaseSensitive(root, "zipBase64");
if (zipBase64Node != NULL && zipBase64Node->type == cJSON_Object) {
// 获取type字段值
cJSON* typeNode = cJSON_GetObjectItemCaseSensitive(zipBase64Node, "type");
if (typeNode != NULL && typeNode->type == cJSON_String) {
printf("Type: %s\n", typeNode->valuestring);
} else {
printf("无法获取Type字段\n");
}
// 获取data字段值
cJSON* dataNode = cJSON_GetObjectItemCaseSensitive(zipBase64Node, "data");
if (dataNode != NULL && dataNode->type == cJSON_Array) {
int dataSize = cJSON_GetArraySize(dataNode);
for (int i = 0; i < dataSize; i++) {
cJSON* element = cJSON_GetArrayItem(dataNode, i);
if (element != NULL && element->type == cJSON_Number) {
printf("[%d]: %d\n", i, element->valueint);
}
}
} else {
printf("无法获取Data字段\n");
}
} else {
printf("无法获取ZipBase64字段\n");
}
// 释放内存
cJSON_Delete(root);
return 0;
}
- 编译并运行该代码。如果一切顺利,你将看到输出结果中包含Site Name、Type和Data字段的相应信息。
请确保在编译和运行此代码之前,已经正确地包含cJSON库,并链接相应的库文件。
希望这可以帮助到你!如有其他问题,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问




