STM32学习笔记之Cjson的使用

解析

需要用到的几个函数:
1、解析JSONJ结构得到cjson对象:cJSON * root=cJSON_Parse(char *buf);
2、获取无格式的json对象:cJSON_PrintUnformatted(cJSON *item)
3、根据键值获取对应的值:cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);

假设一串JSON字符串如下:
{“Address”:“111D6FFFFE12459D”,“CommandType”:“010D”,“EndpointId”:“1”,“Command”:{“Operate”:“0”}}

解析如下:
cjson_command com;//此结构体为接收json各个键值的数据
cJSON * root=cJSON_Parse(char *buf);//buf指向cjson字符串数据

c_add =cJSON_GetObjectItem(root,“Address”);
strcpy(com.Address,c_add->valuestring);

cJSON * c_ctype =NULL;
c_ctype =cJSON_GetObjectItem(root,“CommandType”);
strcpy(com.CommandType,c_ctype->valuestring);
cJSON * c_Epid =NULL;
c_Epid =cJSON_GetObjectItem(root,“EndpointId”);
strcpy(com.Endpointid,c_Epid->valuestring);
cJSON * c_Com =NULL;
c_Com =cJSON_GetObjectItem(root,“Command”);
if(c_Com == NULL)
{
u3_printf(“no command\r\n”);
}else{
cJSON * c_Ope =NULL;
c_Ope =cJSON_GetObjectItem(c_Com,“Operate”);
if(c_Ope == NULL)
{
u3_printf(“no Operate!\r\n”);
}else
{
strcpy(com.Operate,c_Ope->valuestring);
u3_printf(“Operate:%s\r\n”,com.Operate);
}

cJSON_Delete(root);

注意:
我的例子里 json字符串的值全为char类型的,可根据实际情况设置变量,例如c_ctype->valuestring可以为valueint、valuedouble。

合成

STM32学习笔记之Cjson的使用
合成结果如下:
{
“Address”: “1234567890ABCDEF”,
“EndpointId”: “1”,
“State”: {
“State”: “1”
},
“StateType”: “020D”,
“DeviceType”: 1101
}

注意:在合成的时候,发现不能打印出来的情况,无法合成cjson字符串,程序出现跑飞的情况。原因是数据长度过大,堆栈大小不够,导致堆栈溢出。办法是startup_stm32f10x_md.s中调整堆栈大小即可。