例子1、解析JSON
char * json = "{ "json" : { "id":1,"nodeId":11,"deviceId":111,"deviceName":"aaa","ieee":"01212","ep":"1111","type":"bbb" }}";
char * json1 = "{"id":1,"deviceName":"aaa"}";
cJSON * root;
cJSON * format;
int value_int;
char * value_string;
root = cJSON_Parse(json);
format = cJSON_GetObjectItem(root,"json");
value_int = cJSON_GetObjectItem(format,"nodeId")->valueint;
value_string = cJSON_GetObjectItem(format,"ieee")->valuestring;
printf( "%dn",value_int );
printf( "%sn",value_string );
cJSON_Delete(root);
root = cJSON_Parse(json1);
value_int = cJSON_GetObjectItem(root,"id")->valueint;
value_string = cJSON_GetObjectItem(root,"deviceName")->valuestring;
printf( "%dn",value_string );
cJSON_Delete(root);
例子二:生成JSON数据
cJSON* pRoot = cJSON_CreateObject();
cJSON* pArray = cJSON_CreateArray();
cJSON_AddItemToObject(pRoot,"students_info",pArray);
char* szOut = cJSON_Print(pRoot);
cJSON* pItem = cJSON_CreateObject();
cJSON_AddStringToObject(pItem,"name","chenzhongjing");
cJSON_AddStringToObject(pItem,"sex","male");
cJSON_AddNumberToObject(pItem,"age",28);
cJSON_AddItemToArray(pArray,pItem);
pItem = cJSON_CreateObject();
cJSON_AddStringToObject(pItem,"fengxuan");
cJSON_AddStringToObject(pItem,24);
cJSON_AddItemToArray(pArray,"tuhui");
cJSON_AddStringToObject(pItem,22);
cJSON_AddItemToArray(pArray,pItem);
char* szJSON = cJSON_Print(pRoot);
cJSON_Delete(pRoot);
//free(szJSON);
pRoot = cJSON_Parse(szJSON);
pArray = cJSON_GetObjectItem(pRoot,"students_info");
if (NULL == pArray)
{
return -1;
}
int iCount = cJSON_GetArraySize(pArray);
for (int i = 0; i < iCount; ++i)
{
cJSON* pItem = cJSON_GetArrayItem(pArray,i);
if (NULL == pItem)
{
continue;
}
string strName = cJSON_GetObjectItem(pItem,"name")->valuestring;
string strSex = cJSON_GetObjectItem(pItem,"sex")->valuestring;
int iAge = cJSON_GetObjectItem(pItem,"age")->valueint;
}
cJSON_Delete(pRoot);
free(szJSON);