一、解析JSON格式数据 //需要解析的字符串 char *str="{\"action\":\"writePara\",\"value\":{\"id\":\"1\",\"frontId\":\"1\",\"band485\":\"1200\",\"bandCan\":\"10\",\"sidewayTime\":\"10\",\"sidwwaySync\":\"1\",\"upDownTime\":\"10\
一、解析JSON格式数据
//需要解析的字符串
char *str="{\"action\":\"writePara\",\"value\":{\"id\":\"1\",\"frontId\":\"1\",\"band485\":\"1200\",\"bandCan\":\"10\",\"sidewayTime\":\"10\",\"sidwwaySync\":\"1\",\"upDownTime\":\"10\",\"upDownTimeSync\":\"1\",\"hookMode\":\"electric\",\"senseMode\":\"single\",\"isStopCar\":\"1\",\"originalIsStopCar\":\"1\",\"isShiftLeft\":\"1\",\"isShiftRight\":\"1\",\"isShiftUp\":\"1\",\"isShiftDown\":\"1\",\"isRstData\":\"1\"}}";
int main(void)
{
cJSON *root;
cJSON *jsonAction;
cJSON *jsonRWAddr;
while(1)
{
root=cJSON_Parse((const char *)str);
jsonAction = cJSON_GetObjectItem(root,"action"); //获取动作
if(strcmp(jsonAction->valuestring,"writePara")==NULL) //写参数
{
jsonRWAddr = cJSON_GetObjectItem(root,"writeId"); //获取读的ID
modbusReadWriteAddr = atoi16(jsonRWAddr->valuestring,10); //将ID转为int
}
cJSON_Delete(root);
cJSON_Delete(jsonAction);
cJSON_Delete(jsonRWAddr);
}
}
二、生成字符串
int main(void)
{
char *jsonValue;
cJSON *jsonCreat;
cJSON *jsonCreatValue;
jsonCreat = cJSON_CreateObject();//创建一个json对象
jsonCreatValue = cJSON_CreateObject();//创建一个json对象
cJSON_AddItemToObject(jsonCreat, "action", cJSON_CreateString("readPara"));
cJSON_AddItemToObject(jsonCreatValue, "id", cJSON_CreateString("1"));
cJSON_AddItemToObject(jsonCreat, "value", jsonCreatValue);
jsonValue=cJSON_Print(jsonCreat);//打印生成JSON格式数据
cJSON_Delete(jsonCreat);
cJSON_Delete(jsonCreatValue);
printf("%s\r\n",jsonValue);
while(1)
{
}
}
生成的字符串
{action:readPara,value{id:1}}
三、CJSON使用注意点
解析生成字符串需要的堆栈比较大,需要把STM32的堆栈搞大一点
四、完整工程和库文件下载
完整工程下载