ZBLOG

#include #include #include #include "cjson/cJSON.h" int main() { const char* json = "{\"siteName\":\"两江人和停车场换电站-1\",\"zipBase64\":{\"type\":\"Buffer\",\"data\":[80,75,3,4,10,0,0,0,0,0,221,81,142,88,147,159,64,....

要输出 cJSON 数组中的值,可以使用 cJSON 提供的遍历方式来访问数组元素。下面是一个示例代码,演示了如何输出 cJSON 数组中的值:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "cjson/cJSON.h"
  5. int main() {
  6. const char* json = "{\"siteName\":\"两江人和停车场换电站-1\",\"zipBase64\":{\"type\":\"Buffer\",\"data\":[80,75,3,4,10,0,0,0,0,0,221,81,142,88,147,159]}}";
  7. // 解析JSON字符串
  8. cJSON* root = cJSON_Parse(json);
  9. if (root == NULL) {
  10. printf("Failed to parse JSON!\n");
  11. return 1;
  12. }
  13. // 获取zipBase64字段对应的cJSON对象
  14. cJSON* zipBase64Obj = cJSON_GetObjectItem(root,"zipBase64");
  15. if (zipBase64Obj == NULL) {
  16. printf("Failed to get zipBase64 object!\n");
  17. cJSON_Delete(root);
  18. return 1;
  19. }
  20. // 获取数组指针
  21. cJSON* dataArray = cJSON_GetObjectItem(zipBase64Obj, "data");
  22. if (dataArray == NULL || !cJSON_IsArray(dataArray)) {
  23. printf("Failed to get data array!\n");
  24. cJSON_Delete(root);
  25. return 1;
  26. }
  27. // 遍历数组并输出每个元素值
  28. int arraySize = cJSON_GetArraySize(dataArray);
  29. for (int i = 0; i < arraySize; ++i) {
  30. cJSON* element = cJSON_GetArrayItem(dataArray, i);
  31. if (cJSON_IsNumber(element)) {
  32. int value = element->valueint;
  33. printf("Element %d: %d\n", i, value);
  34. }
  35. }
  36. // 清理资源
  37. cJSON_Delete(root);
  38. return 0;
  39. }

在上述示例中,我们首先解析了一个 JSON 字符串,并获取到 zipBase64 字段对应的 cJSON 对象。然后,通过使用 cJSON_GetObjectItem() 函数获取到数组指针。接下来,使用 cJSON_GetArraySize() 函数获取数组的长度,并通过 cJSON_GetArrayItem() 遍历每个数组元素。

注意,在遍历过程中,我们需要使用 cJSON_IsNumber() 来判断元素类型是否为数字类型,然后通过访问 element->valueint 获取具体的数值。

运行示例代码,即可输出数组中的每个元素值。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=13533

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?