目录
一、cJSON的下载
二、cJSON的常用函数
三、cJSON的打包例程
四、cJSON的解析例程1
五、cJSON的解析例程2
一、cJSON的下载
cjson下载
二、cJSON的常用函数
cJSON *cJSON_Parse(const char *value);
作用:将一个JSON数据包,按照cJSON结构体的结构序列化整个数据包,并在堆中开辟一块内存存储cJSON结构体 返回值:成功返回一个指向内存块中的cJSON的指针,失败返回NULL
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
作用:获取JSON字符串字段值 返回值:成功返回一个指向cJSON类型的结构体指针,失败返回NULL
char *cJSON_Print(cJSON *item);
作用:将cJSON数据解析成JSON字符串,并在堆中开辟一块char*的内存空间存储JSON字符串 返回值:成功返回一个char*指针该指针指向位于堆中JSON字符串,失败返回NULL
void cJSON_Delete(cJSON *c);
作用:释放位于堆中cJSON结构体内存 返回值:无
void cJSON_AddItemToArray(cJSON *array, cJSON *item);
void cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
作用:将每一项的内容附加到指定的数组/对象 返回值:无
cJSON_GetArraySize(const cJSON *array);
cJSON *cJSON_GetArrayItem(const cJSON *array, int item);
三、cJSON的打包例程
{
"name":"menglingjun",
"age":21
}
void test_dabao()
{//打包cJSON * root = cJSON_CreateObject();cJSON_AddItemToObject(root, "name", cJSON_CreateString("menglingjun"));//根节点下添加cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(21));//打印printf("%s\n", cJSON_Print(root));
}
四、cJSON的解析例程1
{
"name":"menglingjun",
"age":21
}
void test1_jiexi()
{//解析char jsondata[] = "{\"name\":\"menglingjun\",\"age\":21}"cJSON *json = nullptr,*json_name = nullptr,*json_age = nullptr;json = cJSON_Parse(jsondata);//解析失败if(!json){printf("error:",cJSON_GetErrorPtr());}else{json_age = cJSON_GetObjectItem(json,"age");//类型是数字if(json_age->type == cJSON_Number){printf("age is %d\n",json_age->valueint);}json_name = cJSON_GetObjectItem(json,"name");//类型是字符串if(json_name->type == cJSON_String){printf("name is %s\n",json_age->valuestring);}//释放内存cJSON_Delete(json);}
}
五、cJSON的解析例程2
{
"time":"2018-11-28 09:06:12",
"forecast":[{
"date":"28日星期三",
"sunrise": "07:07",
"high":"高温 11.0C",
"low":"低温 1.0C",
"sunset": "16:50",
"aqi": 116.0,
"fx":"东风",
"fl":"<3级",
"type":"多云",
"notice":"阴晴之间,谨防紫外线侵扰"
},
{
"date":"29日星期四",
"sunrise": "08:07",
"high":"高温 15.0C",
"low":"低温 2.0C",
"sunset": "12:50",
"aqi": 110.0,
"fx":"东风",
"fl":"<3级",
"type":"多云",
"notice":"阴晴之间,谨防紫外线侵扰"
}]
}
void test2_jiexi()
{//解析cJSON *root = cJSON_Parse(buf);if(root == nullptr){printf("parse error\n");}//根据key值获取对应的valuecJSON *value = cJSON_GetObjectItem(root,"time");//将数据转成字符串输出char *date = cJSON_Print(value);printf("time is %s\n",date);free(date);//获取数组对象value = cJSON_GetObjectItem(root,"forecast");//获取数组对象的大小int len = cJSON_GetArraySize(value);printf("len is %d\n",len);//根据下标获取对象 取出第0项int i = 0;cJSON *type_value = nullptr;cJSON *date_value = nullptr;for(i=0;i<len;i++){date_value = cJSON_GetArrayItem(value,i);type_value = cJSON_GetArrayItem(value,i);//获取key对应的valuedate_value = cJSON_GetObjectItem(date_value,"date");type_value = cJSON_GetObjectItem(type_value,"type");//打印char *print1 = cJSON_Print(date_value);char *print2 = cJSON_Print(type_value);printf("date is %s,type is %s\n",print1,print2);free(print1);free(print2);}//释放内存cJSON_Delete(root);
}