// 用cjson.c和cjson.h读取json文件,保存json文件
#include "cJson.h"
/*
// 示例json,名称为1.json
[
{
"ImgName":"abc.jpg"
"ImgInfo":
{
"ImgSize":
[
1920,
1080
]
},
"person":
[
{
"rect":
[
[
25,
30
],
[
150,
200
]
],
"id":1
},
{
"rect":
[
[
25,
30
],
[
151,
201
]
],
"id":2
},
{
"rect":
[
[
25,
30
],
[
152,
202
]
],
"id":3
}
]
}
]
*/
cJSON* Parse_json(std::string picJsonName)
{
char *content; // 文件内容
long len; // 文件长度
FILE *fp_json = NULL; // 文件指针
cJSON *json_input = NULL;
fp_json = fopen(picJsonName.c_str(),"rb"); // c_str: 将string转换为char*
fseek(fp_json,0,SEEK_END); // 文件指针指向尾部
len = ftell(fp_json); // ftell:用于得到文件位置指针当前位置相对于文件首的偏移字节数
fseek(fp_json,0,SEEK_SET); // 文件指针指向头部
content = (char *)malloc(len+1); //为json格式的文件分配内存
fread(content,1,len,fp_json);
fclose(fp_json);
json_input = cJSON_Pare(content); // 解析json接口
free(content);
return json_input;
}
int main()
{
std::string picJsonName = "./data/1.json"
cJSON *json_input = NULL;
cJSON *json_input_temp = NULL;
int input_img_width = 0;
int input_img_height = 0;
int person_num = 0;
int left_up_x = 0;
int left_up_y = 0;
int right_down_x = 0;
int right_down_y = 0;
json_input = Parse_json(picJsonName);
// 获取图像宽高
json_input_temp = cJSON_GetArrayItem((cJSON_GetObjectItem(cJSON_GetObjectItem(json_input,"ImgInfo"),"ImgSize"),0);
input_img_width = json_input_temp->valueint;
json_input_temp = cJSON_GetArrayItem((cJSON_GetObjectItem(cJSON_GetObjectItem(json_input,"ImgInfo"),"ImgSize"),1);
input_img_height = json_input_temp->valueint;
// 获取json中person的个数
person_num = cJSON_GetArraySize(cJSON_GetObjectItem(json_input,"person"));
// 获取json中每个person的四个坐标值
for (int i =0; i < person_num; i++)
{
left_up_x = cJSON_GetArrayItem(cJSON_GetArrayItem(cJSON_GetObjectItem(cJSON_GetArrayItem(cJSON_GetObjectItem(json_input,"person"),i),"rect"),0),0);
left_up_y = cJSON_GetArrayItem(cJSON_GetArrayItem(cJSON_GetObjectItem(cJSON_GetArrayItem(cJSON_GetObjectItem(json_input,"person"),i),"rect"),0),1);
right_down_x = cJSON_GetArrayItem(cJSON_GetArrayItem(cJSON_GetObjectItem(cJSON_GetArrayItem(cJSON_GetObjectItem(json_input,"person"),i),"rect"),1),0);
right_down_y = cJSON_GetArrayItem(cJSON_GetArrayItem(cJSON_GetObjectItem(cJSON_GetArrayItem(cJSON_GetObjectItem(json_input,"person"),i),"rect"),1),1);
printf("%d, %d, %d, %d \n",left_up_x,left_up_y,right_down_x,right_down_y);
}
return 1;
}
C语言 | 解析json
猜你喜欢
转载自blog.csdn.net/qiu931110/article/details/103533979
今日推荐
周排行