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 数组中的值:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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]}}";
    
    // 解析JSON字符串
    cJSON* root = cJSON_Parse(json);
    if (root == NULL) {
        printf("Failed to parse JSON!\n");
        return 1;
    }
    
    // 获取zipBase64字段对应的cJSON对象
    cJSON* zipBase64Obj = cJSON_GetObjectItem(root,"zipBase64");
    if (zipBase64Obj == NULL) {
        printf("Failed to get zipBase64 object!\n");
        cJSON_Delete(root);
        return 1;
    }
    
    // 获取数组指针
    cJSON* dataArray = cJSON_GetObjectItem(zipBase64Obj, "data");
    if (dataArray == NULL || !cJSON_IsArray(dataArray)) {
        printf("Failed to get data array!\n");
        cJSON_Delete(root);
        return 1;
    }
    
    // 遍历数组并输出每个元素值
    int arraySize = cJSON_GetArraySize(dataArray);
    for (int i = 0; i < arraySize; ++i) {
        cJSON* element = cJSON_GetArrayItem(dataArray, i);
        
        if (cJSON_IsNumber(element)) {
            int value = element->valueint;
            printf("Element %d: %d\n", i, value);
        }
    }
    
    // 清理资源
    cJSON_Delete(root);
    
    return 0;
}

在上述示例中,我们首先解析了一个 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

注册

已经有帐号?