网上找了一圈都没有看到直接处理json文件的代码,只看到处理json数据的。所以就自己总结了一个json文件的读取处理代码。直接上代码
#include
#include "cJSON.h"
int main()
{
const char* version = cJSON_Version();
printf("version:%s\n", version);
FILE* file = fopen("./test.json", "r");
if(NULL == file)
{
printf("load file fail!\n");
return -1;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
char* tmpStr = (char*)malloc(size + 1);
memset(tmpStr, 0, size + 1);
size_t ret = fread(tmpStr, size, 1, file);
tmpStr[size] = '\0';
printf("ret = %d size = %ld str=%s\n", ret, size, tmpStr);
cJSON* root = cJSON_Parse(tmpStr);
cJSON* map_id = cJSON_GetObjectItem(root,"map_id");
if(NULL != map_id)
printf("mapid is %d\n",map_id->valueint);
cJSON *rect = cJSON_GetObjectItem(root, "rect");
if(NULL != rect)
{
if(cJSON_IsArray(rect))
{
int len = cJSON_GetArraySize(rect);
for(int i = 0; i < len; i++)
{
cJSON* pos = cJSON_GetArrayItem(rect, i);
printf("i=%d value = %d\n", i, pos->valueint);
}
}
else
{
printf("the rect is not an array!\n");
}
}
else
{
printf("rect is null\n");
}
cJSON *areas = cJSON_GetObjectItem(root,"areas");
if(NULL != areas)
{
if(cJSON_IsArray(areas))
{
int num = cJSON_GetArraySize(areas);
cJSON* area = areas->child;
for(int i = 0;ivalueint);
cJSON* name = cJSON_GetObjectItem(area,"name");
printf("name = %s\n",name->valuestring);
cJSON* rect = cJSON_GetObjectItem(area,"rect");
{
if(cJSON_IsArray(rect))
{
int n = cJSON_GetArraySize(rect);
for(int j = 0;jvalueint);
}
}
}
else
{
printf("not a array\n");
}
}
area = area->next;
}
}
else
{
{
printf("the areas is not a array\n");
}
}
}
else
{
printf("areas is null\n");
}
fclose(file);
free(tmpStr);
return 0;
}
json格式如下:包括了数组及嵌套数组等json数据的操作
{
"map_id":1,
"map_name":"map1",
"device_id":"device1",
"timestamp":123456,
"rect":[100,200,400,600],
"area_cnt":"area_cnt",
"areas":[
{
"id":0,
"name":"area1",
"rect":[100,100,100,100]
},
{
"id":1,
"name":"area2",
"rect":[200,200,200,200]
},
{
"id":3,
"name":"area3",
"rect":[300,300,300,300]
}
]
}
使用方法:去github上下载一个cjson.h和cjson.cpp,再将自己的read.cpp放到和他们同一级的目录下一起编译,linux和Windows下都能编译。
读取结果如下:
如果找不到json文件就去我的github上找:https://github.com/hddid/Utils,在我的utils下面。