C语言读取JSON文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stSahana/article/details/79638992

用来读取json文件并赋值给对象,使用了cJSON

typedef struct {
    cJSON *url;
    char path[100];
    char app_name[100];
} Enter;

int main(){
    FILE *f;//输入文件
    long len;//文件长度
    char *content;//文件内容
    cJSON *json;//封装后的json对象
    f=fopen("./test.json","rb");
    fseek(f,0,SEEK_END);
    len=ftell(f);
    fseek(f,0,SEEK_SET);
    content=(char*)malloc(len+1);
    fread(content,1,len,f);
    fclose(f);

    json=cJSON_Parse(content);
    if (!json) {
        printf("Error before: [%s]\n",cJSON_GetErrorPtr());
    }
    Enter weixin;
    //char *out=cJSON_Print(json);
    strcpy(weixin.app_name,cJSON_GetObjectItem(json,"app_name")->valuestring);
    strcpy(weixin.path,cJSON_GetObjectItem(json,"path")->valuestring);
    weixin.url=cJSON_GetObjectItem(json,"url");
    //打印字符串
    printf("app_name:%s",weixin.app_name);
    //打印字符串数组
    int array_size=cJSON_GetArraySize(weixin.url);
    cJSON *item;
    int i;
    for(i=0; i< array_size; i++) {  
        item = cJSON_GetArrayItem(weixin.url, i);   
        printf("%s\n",item->valuestring);  
    }  
    retutn 0;
}

猜你喜欢

转载自blog.csdn.net/stSahana/article/details/79638992