/*reference documentationhttps://blog.csdn.net/stsahana/article/details/79638992
https://blog.csdn.net/fengxinlinux/article/details/53121287
*/#include#include#include#include#include"cJSON.h"
char *json_file_path = "./railwayFence.json";char *json_loader(char *path)
{
FILE*f;longlen;char *content;
f=fopen(path,"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);returncontent;
}int main(void)
{char *json_str =json_loader(json_file_path);
cJSON*root=cJSON_Parse(json_str);if (!root) {
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}//railwayFence array
cJSON *railwayFenceArray = cJSON_GetObjectItem(root, "railwayFence");if(!railwayFenceArray){
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}int railwayFence_array_size =cJSON_GetArraySize(railwayFenceArray);
printf("railwayFence array size is %d\n",railwayFence_array_size);int i = 0;char *p =NULL;
cJSON*it;for(i=0; i< railwayFence_array_size; i++) {
cJSON*railwayFenceItem =cJSON_GetArrayItem(railwayFenceArray,i);
p=cJSON_PrintUnformatted(railwayFenceItem);
it=cJSON_Parse(p);if(!it)continue;
cJSON*areaName,*dangerType;
areaName= cJSON_GetObjectItem(it, "areaName");
printf("areaName is %s\n",areaName->valuestring);
dangerType= cJSON_GetObjectItem(it, "dangerType");
printf("dangerType is %s\n",dangerType->valuestring);//Coordinate array
cJSON *CoordinateArray = cJSON_GetObjectItem(railwayFenceItem, "coordinates");if(!CoordinateArray){
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}int Coordinate_array_size =cJSON_GetArraySize(CoordinateArray);
printf("Coordinate array size is %d\n",Coordinate_array_size);int j = 0;char *q =NULL;
cJSON*jt;for(j=0; j< Coordinate_array_size; j++) {
cJSON*CoordinateItem =cJSON_GetArrayItem(CoordinateArray,j);
q=cJSON_PrintUnformatted(CoordinateItem);
jt=cJSON_Parse(q);if(!jt)continue;
cJSON*B,*L;
B= cJSON_GetObjectItem(jt, "B");
printf("B is %f\n",B->valuedouble);
L= cJSON_GetObjectItem(jt, "L");
printf("L is %f\n",L->valuedouble);free(q); cJSON_Delete(jt);
}free(p); cJSON_Delete(it);
}if(root) {
cJSON_Delete(root);//return 0;
}return 0;
}