遇到一个需求,解析BSM消息的JSON包,网上下载cJSON.h和cJSON.h,然后解析BSM1.json文件。
BSM1.json文件内容如下:
{
"ego_infor":[
{
"msgCnt":0,
"id":15416284,
"timeStamp":"1.615275863e+12",
"latitude":31.00083665,
"longitude":121.0002046,
"elevation":"",
"speed":0,
"heading":90,
"length":400,
"width":180,
"safeExt":{
"aaa":1,
"bb":1
}
},
{
"msgCnt":1,
"id":15416284,
"timeStamp":"1.615275863e+12",
"latitude":31.00083665,
"longitude":121.0002046,
"elevation":"",
"speed":0.0005859375,
"heading":90,
"length":400,
"width":180,
"safeExt":{
"aaa":2,
"bb":2
}
}
]
}
解析代码如下:
#include <stdio.h>
#include "cJSON.h"
#include <stdlib.h>
FILE *fp = NULL;
cJSON *json;
char *out;
char *line = NULL;
int main() {
fp = fopen("D:\\bsm1.json", "r");
if(NULL == fp)
{
printf("load file fail!\n");
return -1;
}
fseek(fp,0L,SEEK_END); /* 定位到文件末尾 */
int length = ftell(fp);
printf("ftell:%d\n",length);
line = (char*)malloc(sizeof(char)*(length+1));
fseek(fp,0L,SEEK_SET); /* 定位到文件开头 */
fread(line,length,sizeof(char),fp);
//printf("line:%s\n",line);
json=cJSON_Parse(line); //获取整个大的句柄
// out=cJSON_Print(json); //这个是可以输出的。为获取的整个json的值
cJSON *arrayItem = cJSON_GetObjectItem(json,"ego_infor"); //获取这个对象成员
cJSON *object = cJSON_GetArrayItem(arrayItem,1); //因为这个对象是个数组,获取第一个元素所以写下标为0
cJSON *item = cJSON_GetObjectItem(object,"msgCnt");
printf("msgCnt:%d\n",item->valueint);
item = cJSON_GetObjectItem(object,"id");
printf("id:%ld\n",item->valueint);
item = cJSON_GetObjectItem(object,"timeStamp");
printf("timeStamp:%s\n",item->valuestring);
cJSON_Delete(json);
close(fp);
free(line);
}
cJSON文件下载链接:下载链接